How to Set the Background Color of a JButton on the Mac OS
Solution 1
Have you tried setting JButton.setOpaque(true)?
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);
Solution 2
Have you tried setting the painted border false?
JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);
It works on my mac :)
Solution 3
If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.
Stephane Grenier
Author of the book Blog Blazers. Blog author of FollowSteph.com Founder of LandlordMax Property Management Software
Updated on July 20, 2021Comments
-
Stephane Grenier almost 3 years
Normally with Java Swing you can set the background color of a button with:
myJButton.setBackground(Color.RED);
which would cause the button to be red. But on the Mac OS, this method seems to be ignored. The button just stays the default color.
How can the color of a JButton be set on the Mac OS?
-
Stephane Grenier almost 15 yearsThanks. I completely missed the setOpaque() call.
-
Reed Richards over 10 yearsSeems that you need to add a setBorderPainted(false) command in order to get the button to opaque(Java 6 on Mavericks).
-
Timothy Swan over 9 yearsOk, this isn't the mac version of setting windows JButton background though. It literally only sets the background behind the button but on windows the button color can be changed. How do you change the gray mac button itself to be another color?
-
Timothy Swan over 9 yearsYes, this should actually be the correct answer when trying to get the same results from Window's perspective. Thank you.
-
Mischa about 9 yearsThis doesn't work for me on Windows 7 / Java 8. The button's surface remains gray, only the bit of the background around the button changes the colour.
-
humanity about 8 yearsGlad to have found this. I needed both setLookAndFeel() and setOpaque(true)
-
BNetz over 7 yearsThis was the solution for me on Mac OS 10.11 / Java 8. Thanks!
-
Lapis Diamond over 7 yearsHe never mensioned myButton.setOpaque(true);
-
TT. over 6 yearsHow many more times do you feel the same answer should be repeated?
-
htlbydgod over 6 yearsSince different combinations get differing results, the post it. Okay, got your suggestion. Thanks.