Paint - Double click on any color at the bottom of the screen. - Choose "Define Custom Colors". - Select a color and/or use the arrows to achieve the desired color. are the numbers needed to create your new Java color.
Retrieve the content pane for the frame and use the setBackground() method inherited from Component to change the color.
Example:
myJFrame.getContentPane().setBackground( desiredColor );
To set the background color for JFrame:
getContentPane().setBackground(Color.YELLOW); //Whatever color
using:
setBackground(Color.red);
doesn't work properly.
use
Container c = JFrame.getContentPane();
c.setBackground(Color.red);
or
myJFrame.getContentPane().setBackground( Color.red );
To set the background color for the JFrame try this:
this.getContentPane().setBackground(Color.white);
Hello There I did have the same problem and after many attempts I found that the problem is that you need a Graphics Object to be able to draw, paint(setBackgroundColor).
My code usually goes like this:
import javax.swing.*;
import java.awt.*;
public class DrawGraphics extends JFrame{
public DrawGraphics(String title) throws HeadlessException {
super(title);
InitialElements();
}
private void InitialElements(){
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// This one does not work
// getContentPane().setBackground(new Color(70, 80, 70));
}
public void paint(Graphics draw){
//Here you can perform any drawing like an oval...
draw.fillOval(40, 40, 60, 50);
getContentPane().setBackground(new Color(70,80,70));
}
}
The missing part on almost all other answers is where to place the code. Then now you know it goes in paint(Graphics G)
This is the simplest and the correct method. All you have to do is to add this code after initComponents();
getContentPane().setBackground(new java.awt.Color(204, 166, 166));
That is an example RGB color, you can replace that with your desired color. If you dont know the codes of RGB colors, please search on internet... there are a lot of sites that provide custom colors like this.
You can use a container like so:
Container c = JFrame.getContentPane();
c.setBackground(Color.red);
You must of course import java.awt.Color
for the red color constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With