35

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
  • 15,527
  • 38
  • 117
  • 192

5 Answers5

53

Have you tried setting JButton.setOpaque(true)?

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);
codethulhu
  • 3,976
  • 2
  • 21
  • 15
  • Thanks. I completely missed the setOpaque() call. – Stephane Grenier Jul 02 '09 at 14:40
  • 7
    Seems that you need to add a setBorderPainted(false) command in order to get the button to opaque(Java 6 on Mavericks). – Reed Richards Nov 26 '13 at 16:29
  • 13
    Ok, 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 Sep 24 '14 at 17:50
42

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 :)

MrSmileFace
  • 421
  • 4
  • 2
  • 7
    Yes, this should actually be the correct answer when trying to get the same results from Window's perspective. Thank you. – Timothy Swan Sep 24 '14 at 17:52
  • 1
    This 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. – Mischa May 10 '15 at 13:13
  • This was the solution for me on Mac OS 10.11 / Java 8. Thanks! – BNetz Dec 10 '16 at 22:19
26

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.

JoJo
  • 261
  • 3
  • 2
1

I own a mac too! here is the code that will work:

myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works

before doing anything or adding any components set the look and feel so it looks better:

try{
   UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
 }catch(Exception e){
  e.printStackTrace(); 
 }

That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)

-2

Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose

htlbydgod
  • 330
  • 2
  • 8