Search code examples
javaswingjbutton

Changing the background of JButton


I have a Swing JButton and I'm also using the following code for my project:

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

Now when trying to change the background for one button using btnNewButton.setBackground(Color.RED); it doesn't turn red, only the borders turn red.

How can I turn this background to red while still using UIManager.getSystemLookAndFeelClassName() for the rest of the components/project?


Solution

  • Take a look at bug 4880747 : XP L&F: REGRESSION: setBackground on JButton sets border color in Windows XP. Evaluation section states:

    Changing the appearance of a button can always cause conflicts with the current L&F implementation. The Windows L&F for Swing tries to be as close as possible to the native display. On XP, we use the built-in bitmap resources for the buttons. These can not be colorized, just like in the native API.

    You should call setContentAreaFilled(false) on the button to avoid having the L&F paint its decorations. This has the side effect that the button's opaque property is set to false, so you need to follow that call with a call to setOpaque(true).

    This is not a bug and will be closed.

    As stated, setContentAreaFilled(false) and setOpaque(true) will do the trick, but the button will look different.

    If it worth the trouble you can create you own ButtonUI. Here is a great example by @mKorbel that you may find useful.