Reputation: 1091
I have a JTable with 3 columns in it. 1. Icon, 2. Name of file or folder, 3. File type or "Folder". I draw the Icon using a JLabel (I set background + png image) within the getTableCellRendererComponent
method. Initially I draw an alternating background of the JLable either "white" or "grey" since those are the colors that the JTable
Swing component alternates to draw the table. Now, when I select a row, the Icon (the first column) background does not get redrawn to "dark blue" same as the rest of the row.
Here are my questions:
General 1) How can also highlight the Icon cell when highlighting a row (pointers will suffice, no code expected)?
Specific
1.1) Do I have to use JLabel? Why can't I just e.g. .SetValueAt("image.png",0,0)
1.2) I tried the getColumnClass(...)
but that seems to redraw ALL cells in a given column. Is that expected?
Thanks.
Upvotes: 2
Views: 916
Reputation: 51525
assuming the striping (alternate white/grey background) happens automatically in your LAF (Nimbus?), you shouldn't need a custom renderer: the table already has a default renderer registered for Icon and ImageIcon class. Make sure your tableModel returns one of those classes as columnClass for the first column and enjoy the automatics :-)
Here's a quick code snippet:
DefaultTableModel model = new DefaultTableModel(0, 2) {
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return Icon.class;
}
return super.getColumnClass(columnIndex);
}
};
File[] files = new File(".").listFiles();
FileSystemView fsv = FileSystemView.getFileSystemView();
for (File f : files) {
model.addRow(new Object[] {fsv.getSystemIcon(f), fsv.getSystemDisplayName(f)});
}
JTable table = new JTable(model);
Upvotes: 3
Reputation: 3325
1.) The javax.swing.table.TableCellRenderer
gets an isSelected
parameter when it is called. You can easily write your own TableCellRenderer
by inheriting from JLabel
(for example) and overridding getTableCellRendererComponent
: Adjust the Object and return this
. Having your own renderer also allows you to set a breakpoint and really understand what is happening.
1.1 + 1.2.) Both setValueAt
and getColumnClass
are part if the model and will probably not solve your problem with the selected background.
You do not have to use JLabel
: If you look at the return type from getTableCellRendererComponent
you notice it is Component
(not even JComponent
). I guess JLabel
is just customary because it normally has all the features you want for the renderer and the DefaultTableCellRenderer
also uses JLabel
. For the most freedom I advise you to use JComponent
and write your own paintComponent
, but in this case you probably don't have to do that.
Upvotes: 5