Search code examples
swingjbuttonnimbus

JButton background on Nimbus LAF


I use Nimbus LAF and I want to change the background of a simple JButton.

JButton jbutton = new JButton("test");
jbutton.setBackground(Color.BLACK);

But it doesn't work, when I change the look and feel it works but it doesn't work in Nimbus.

How can i do it?

Thanks for your help.


Solution

  • Nimbus uses Painter to paint the different Styles. By Default the Button has a gradient not a single Color. See Button: Nimbus Defaults List

    You can write your own Painter and override the default. Or you override the background color with the key "Button.background" and use the Default Painter.

    UIDefaults overrides = new UIDefaults();
    overrides.put("Button.background", Color.RED);
    jbutton.putClientProperty("Nimbus.Overrides", overrides);
    jbutton.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
    SwingUtilities.updateComponentTreeUI(jbutton);
    

    Or if you want to change the Color for all Buttons, try:

    UIDefaults defaults = UIManager.getLookAndFeelDefaults();
    defaults.put("Button.background",  Color.RED);
    

    Btw. The JButton bases on the Nimbus default key "nimbusBase", if you change this color :

    UIDefaults defaults = UIManager.getLookAndFeelDefaults();
    defaults.put( "nimbusBase", Color.RED );
    

    then you change everything that uses the nimbus defalut-blue or a secondary color into your new color, not only the Buttons.

    I found a nice Nimbus Theme Creator, which can show the effect of changing a Nimbus Default Color to all Components: http://aephyr.googlecode.com/svn/trunk