JTable TableCellRenderer background with NimbusLookAndFeel color problem
I'm using NimbusLookAndFeel. With this look and feel JTable's cell background are alternatively whi开发者_如何学Pythonte and light grey (it depends on the row number). Now, I'm writing some custom cell renderer implementing TableCellRenderer. I need to set the background of these renderers according to the position of the cell in the JTable.
public class MyCellRenderer extends JLabel implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Color bgColor = //need to retrieve the right cell background color
setBackground(bgColor);
return this;
}
}
How can I get such a Color value?
Technically, you can access the color via the UIManager
Color alternate = UIManager.getColor("Table.alternateRowColor");
Practically, I would not recommend to write renderers from scratch - there are many details to consider to get it right. Those details are handled f.i. in SwingX (biased me :-)
Expected you to do the logic yourself ;-). Here's a working snippet (assuming you want to color by row not by column, but changing that would be ... trivial):
TableCellRenderer renderer = new TableCellRenderer() {
JLabel label = new JLabel();
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
label.setOpaque(true);
label.setText("" + value);
Color alternate = UIManager.getColor("Table.alternateRowColor");
if (row % 2 == 1) {
label.setBackground(alternate);
} else {
label.setBackground(Color.WHITE);
}
return label;
}
};
table.setDefaultRenderer(Object.class, renderer);
This should work perfectly :
public class MyRenderer extends DefaultTableCellRenderer { ... }
精彩评论