Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

swing - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...