Home > Software design >  Change JButton background color
Change JButton background color

Time:05-08

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?

CodePudding user response:

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

CodePudding user response:

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, for example...

JButton b1 = new JButton("Test");
b1.setBackground(Color.BLACK);
add(b1);

JButton b2 = new JButton("Test2");
b2.setBackground(Color.MAGENTA);
add(b2);

enter image description here

In most cases, the button is transparent by default (in my experience), so if instead we did something like 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);

we'd end up with...

enter image description here

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

enter image description here

Sooo, technically, we've changed the background of the button, but I'd 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")

  • Related