简体   繁体   中英

Designing simple cell renderer for Nimbus look and feel

I have a simple-ish cell renderer which is composed of a few JLabel s (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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM