'Change JButton background color
This is what my code looks like:
//color selection (all First column element)
JButton A1 = new JButton("");
A1.setBackground(Color.BLACK);
A1.setContentAreaFilled(false);
A1.setBounds(0, 288, 44, 29);
contentPane.add(A1);
JButton A2 = new JButton("");
A2.setBackground(Color.MAGENTA);
A2.setContentAreaFilled(false);
A2.setBounds(0, 316, 44, 29);
contentPane.add(A2);
No matter how I change it, it seems like there's an incompatible issue between color and button. I tried to use setOpaque and other methods but still did not work.
How to change the background color of a JButton?
Solution 1:[1]
The "problem" - most look and feels will, generally, ignore the background color when rendering the buttons and apply there own internal stylings, for example, on MacOS. this...
JButton b1 = new JButton("Test");
b1.setBackground(Color.BLACK);
add(b1);
JButton b2 = new JButton("Test2");
b2.setBackground(Color.MAGENTA);
add(b2);
will produce this...
In most cases, the button is transparent by default (in my experience), so instead we need to do something like...
JButton b1 = new JButton("Test");
b1.setBackground(Color.BLACK);
b1.setOpaque(true);
add(b1);
JButton b2 = new JButton("Test2");
b2.setBackground(Color.MAGENTA);
b2.setOpaque(true);
add(b2);
which would produce...
This is because the look and feel is applying it's own styling (via the borderPainted property)
So, if instead, we did something like...
JButton b1 = new JButton("Test");
b1.setBackground(Color.BLACK);
b1.setOpaque(true);
b1.setBorderPainted(false);
add(b1);
JButton b2 = new JButton("Test2");
b2.setBackground(Color.MAGENTA);
b2.setOpaque(true);
b2.setBorderPainted(false);
add(b2);
we'd end up with...
Sooo, technically, we've changed the background of the button, but I don't know about you, this is not what I would really want. There's no "simple" way you could change the background color of the "border" been used (at least not that I've found which is cross platform independent). The "only" solution would would have is to create a new look and feel delegate which could some how provide the fill color for the button border and renderer it yourself, but that is a LOT of work if you want to use it across different platforms (and I've looked into trying to make one for MacOS and gave up, because MacOS has to be "different")
Solution 2:[2]
You need to get rid of the setContentAreaFilled(false) in order to apply your background colors to the JButton.
JButton A1 = new JButton("Test");
A1.setBackground(Color.BLACK);
A1.setBounds(0, 288, 44, 29);
contentPane.add(A1);
JButton A2 = new JButton("Test2");
A2.setBackground(Color.MAGENTA);
A2.setBounds(0, 316, 44, 29);
contentPane.add(A2);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Dan |



