Java Reference
In-Depth Information
In this case, the number of columns is always equal to the number of header titles, so this
method can simply return the length of the headerNames member. Our TableModel must also
return the name of each column. Listing 8-12 returns the String value from the headerNames
member at a specified index.
Listing 8-12. The TableModel's getColumnName Method
public String getColumnName (int column) {
return headerNames[column];
}
Next, the TableModel returns and sets a cell value at a given row and column index. The
methods shown in Listing 8-13 allow the assignment and retrieval of values at specific row and
column indexes.
Listing 8-13. The TableModel's set and get valueAt Methods
public Object getValueAt(int row, int column) {
String[] rowValues = this.dvdRecords.get(row);
return rowValues[column];
}
public void setValueAt(Object obj, int row, int column) {
Object[] rowValues = this.dvdRecords.get(row);
rowValues[column] = obj;
}
Note, it would have been possible for the getValueAt method to have been written as
public Object getValueAt(int row, int column) {
return this.dvdRecords.get(row)[column];
}
Whenever you are tempted to take a shortcut like this, though, you should consider what
benefit it gives you. Is the creation or destruction of the rowValues reference to the array so
expensive that this will gain much efficiency? Alternatively, will this code be harder to read
and therefore harder to maintain?
Next, the method getRowCount shown in Listing 8-14 returns the number of data rows
encapsulated in the TableModel . In our TableModel , the number of rows is the size of the DVD
ArrayList .
Listing 8-14. The DVDTableModel's getRowCount Method
public int getRowCount() {
return this.dvdRecords.size();
}
The isCellEditable method in our TableModel class (see Listing 8-15) indicates whether
or not a cell is editable. No cells in our particular TableModel implementation are editable, so
the method returns false by default. If particular cells in the TableModel were editable, this
Search WWH ::




Custom Search