I am making a GUI interface and I am trying to change the background and foreground color of my windows with the following code:
public class Test
public static void changeColor(String typeOfColor, Component component, Color color)
else if (typeOfColor.equals("Foreground"))
if (component instanceof Container)
for (Component child : ((Container) component).getComponents())
changeColor(typeOfColor, child, color);
public static void main(String args)
JPanel panel = new JPanel();
JButton cancelButton = new JButton("Cancel");
changeColor("Background", panel, new Color(0, 255, 0));
JFrame frame = new JFrame("Frame");
However, no matter what is the color I choose, the buttons still display the background color as grey. How do I change the background color properly? I have looked around and most answers mention the setBackground method, but that does not work for me.
Thanks in advance!
Check on your current program the order of these lines:
panel.add(cancelButton); changeColor("Background", panel, new Color(0, 255, 0));
If you have them in this order you get this output:
But if you change the order:
changeColor("Background", panel, new Color(0, 255, 0)); panel.add(cancelButton);
You get this:
Nicholas Smith solved my issue.
In the comments, he mentioned "It could be the background color for a JButton in your specific LookAndFeel can't be overridden."
I was setting the look and feel in my code and once I removed that part of the code, my buttons' background color was changed successfully.
Thanks to you!
You should change the
LookAndFeel of your GUI with
It happened to me several times in MacOSX