
120
|
Chapter 3, Tables and Trees
#23 Let Your JTables Do the Sorting
HACK
When run, the table will be sorted by column 0, which contains Strings, as
seen in Figure 3-5.
If you click the Sort 2 button (yes, the numbering is human-readable, and
thus it’s one greater than actual column indices), the table will immediately
sort by the
Integers in the middle column, as seen in Figure 3-6.
The color column is next. Click Sort 3 to see the table sort by the colors, as
seen in Figure 3-7.
Component returnMe =
super.getTableCellRendererComponent (table, value,
isSelected,
hasFocus, row, col);
if (value instanceof Color) {
Color color = (Color) value;
returnMe.setBackground (color);
if (returnMe instanceof JLabel) {
JLabel jl = (JLabel) returnMe;
jl.setOpaque(true);
jl.setText ("");
}
}
return returnMe;
}
}
Figure 3-5. JTable sorted automatically by its first column
Example 3-11. The Comparator and TableCellRenderer handle color values in sorting a
table test (continued)