views:

688

answers:

1

I have a simple-ish cell renderer which is composed of a few JLabels (the renderer itself extends JPanel) and I'm trying to get it to render sensibly in the Nimbus look and feel. Basically what is happening is that in the lighter rows (as Nimbus has alternate row coloring), my specific cell renderer is using the table background color (which is much darker than both lighter and the darker row colors). In my renderer I do:

if (isSelected) {
    setBackground(table.getSelectionBackground);
}
else {
    setBackground(table.getBackground);
}

If I comment this whole block of code out then then all my rows are in the darker row color (not the table background, but not in alternate colors either). I'm not sure I even understand what can be going on! How is the above snippet of code producing cells with different background colors at all? Is the table.getBackground color changing between invocations of my method?

I've tried using this snippet of code:

Color alternateColor = sun.swing.DefaultLookup.getColor(
                         peer, 
                         peer.getUI, 
                         "Table.alternateRowColor");
if (alternateColor != null && row % 2 == 0)
    setBackground(alternateColor);

Which is in the DefaultTableCellRenderer class. And it doesn't seem to have any affect at all. Has anyone got custom cell renderers working with Nimbus?

EDIT: If anyone is interested, this turned out to be a problem with Scala table cell renderers, as I was actually using Scala, not Java. The accepted answer below works just fine in a Java program. Separate question filed here.

+2  A: 

Your first piece of code if fine.I think you have to use UIManager.getColor("Table.alternateRowColor") for alternate rows and table.getBackground() otherwise. For selected row use table.getSelectionBackground(). So your code might look like

if (isSelected) {
    setBackground(table.getSelectionBackground());
}
else {
    if ( row % 2 == 0 ) {
       setBackground(UIManager.getColor("Table.alternateRowColor"));
    } else { 
       setBackground(table.getBackground());
    }
}

Don't forget to make sure that your panel is opaque and the labels are transparent.

Here is a good link to Nimbus UI defaults: http://www.duncanjauncey.com/java/ui/uimanager/UIDefaults_Java1.6.0_11_Windows_2000_5.0_Nimbus.html

eugener
Yes - this is *exactly* what I tried and it didn't work. However, I'm actually using Scala, not Java, so I decided to knock up a quick test case in Java and it worked. So thanks. Unfortunately I have no idea why it doesn't work in Scala!
oxbow_lakes
Even though I don't know much about Scala, I don't see a reason why it should not work. Swing is Swing, even in Scala.
eugener