How to change background color in Java panel?

Right now, the background that I am getting is gray. I want to change it to black. I tried to do something like setBackground (color.BLACK); but it didn’t work. Any suggestions?

public test() { setTitle("Adjustment Form"); setSize(670,450); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setLayout(new GridLayout(4,6,2,2)); setVisible(true); } 
+7
java background-color
source share
4 answers

You may call:

 getContentPane().setBackground(Color.black);
getContentPane().setBackground(Color.black); 

Or add a JPanel to the JFrame you are using. Then add your components to JPanel. This will allow you to call

 setBackground(Color.black);
setBackground(Color.black); 

on JPanel to set the background color.

+16
source share

I think he is trying to say it using getContentPane().setBackground(Color.the_Color_you_want_here)

but if you want to set the color for any other, then JFrame, you use object.setBackground(Color.the_Color_you_want_here)

For example:

 jPanel.setbackground(Color.BLUE) 
+4
source share

setBackground() is the correct method. Did you repaint it after you changed it? If you change it before making the panel (or its containing frame) visible, it should work

0
source share

I assume we are dealing with a JFrame? Visible part in the content area - you need to use jframe.getContentPane (). SetBackground (...);

0
source share

All Articles