Java Reference
In-Depth Information
number of subaccounts defined for the account. Since we're defining our
AbstractTableModel as an inner class, we have access to the data in the outer
( BudgetPro ) class. We use the instance variable current , which refers to
whichever account we're currently working with. A quick check of the Account
class shows that an Account object can return the number of subaccounts
(or “children”) via its size() method. So for our getRowCount() method we
return current.size() —provided that current is not null . If it is null ,
we return 1 rather than 0 , so that the table itself shows up and the headings
appear. (But it also means that getValueAt() has to deal with requests for
data from the first row when data may not exist.)
The core of what makes our data appear is the getValueAt() method,
lines 161-185. Since each row represents a subaccount of the current account,
we'll just iterate through current 's list of subaccounts until we reach the
row -th subaccount; for example, to get the third row we iterate over this list of
subaccounts until we get to the third one returned by the iterator's next()
method. This is a bit “brute force,” to keep marching over the list of accounts,
but for our small data size it's not bad. (Another approach would be to change
the Account class to provide a method to return the n -th subaccount. Then it
can use its internal knowledge of the way it stores subaccounts to provide a
more efficient access. Alternately, our extended AbstractTableModel could
iterate over the list once and store the subaccounts in an array, for quicker access
later; the trick here is that the array needs to be refreshed every time the account
changes—so we took the simple approach.)
Once we have a row selected, we use the switch/case construct to choose
the correct data for the requested column. (See the listing in Example 16.2,
lines 173-183.)
The return value for getValueAt() is an Object. Here's one situation
where that is very useful. Refer to the definition of the Account object and
you'll see that getName() returns a String , but getOwner() returns a User
and getTotal() returns an SAMoney object. Since retval is the most generic
type, Object , it can handle all three results.
But how does JTable deal with these odd types? How can it display an
SAMoney object when it doesn't know what one is? There is both a simple and
a complicated answer to that question; we'll try to give you both.
16.7.2.9
The simple answer is that JTable , to display the data returned by
getValueAt() , will call the toString() method on the object. As long as we
Renderers
Search WWH ::




Custom Search