A table model is responsible for managing the data that a JTable displays.
Entries in a JTable are referred to by row and column indexes, but a TreeMap does not have this kind of arrangement. We can still refer to entries in a TreeMap as if they were indexed, by iterating the entry set with a counter.
This is similar to, for example, iterating a linked list to retrieve an element by index.
To do the bare minimum, AbstractTableModel
only requires that getRowCount
, getColumnCount
and getValueAt
are implemented.
If you need the model to be editable, then implementing it gets more complicated.
class TreeMapTableModel extends AbstractTableModel {
private TreeMap<?, ?> data;
TreeMapTableModel(TreeMap<?, ?> data) {
this.data = data;
}
private Map.Entry<?, ?> getEntryFor(int row) {
int index = 0;
for( Map.Entry<?, ?> entry : data.entrySet() ) {
if( index == row )
return entry;
index++;
}
throw outOfBounds("row", row);
}
@Override
public Object getValueAt(int row, int column) {
Map.Entry<?, ?> entry = getEntryFor( row );
switch( column ) {
case 0: return entry.getKey();
case 1: return entry.getValue();
default: throw outOfBounds("column", column);
}
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return 2;
}
private static IndexOutOfBoundsException outOfBounds(
String parameter, int value) {
return new IndexOutOfBoundsException(
parameter + "=" + value);
}
}