Setting background color for a JFrame

462,616

Solution 1

Retrieve the content pane for the frame and use the setBackground() method inherited from Component to change the color.

Example:

myJFrame.getContentPane().setBackground( desiredColor );

Solution 2

To set the background color for JFrame:

getContentPane().setBackground(Color.YELLOW);  //Whatever color

Solution 3

using:

setBackground(Color.red);

doesn't work properly.

use

Container c = JFrame.getContentPane();

c.setBackground(Color.red);

or

myJFrame.getContentPane().setBackground( Color.red );

Solution 4

To set the background color for the JFrame try this:

this.getContentPane().setBackground(Color.white);

Solution 5

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.

Share:
462,616
Admin
Author by

Admin

Updated on February 22, 2021

Comments

  • Admin
    Admin about 3 years

    Just how do you set the background color for a JFrame?

  • kleopatra
    kleopatra over 11 years
    nothing new compared to the older answers, is there ;-) Plus a couple of no-nos: a) don't extend if you can achieve to requirement without b) don't keep alias members c) don't do without LayoutManager
  • kleopatra
    kleopatra about 11 years
    this is either wrong or duplicated, depending on where you want to call the method, on the frame directly or on its contentpane
  • Filipe Brito
    Filipe Brito over 8 years
    Why to answer if there is already the same answer made by other users?
  • crackerplace
    crackerplace about 8 years
    his first statement makes sense i.e setBackGround doesn't work properly.
  • 3.14ed_Piper
    3.14ed_Piper almost 8 years
    not only is that not specified in the answer you gave, but its a repeat of what is answered above.
  • midhunhk
    midhunhk over 7 years
    I feel this is a suggestion for a solution which may or may not be the answer. If the OP tries this and finds it to be working, they can ask you to add as answer to mark it so. This is how I usually work.
  • Tom Aranda
    Tom Aranda over 6 years
    Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
  • Learning
    Learning over 6 years
    I answered concretely, with the code that solves the problem that the person with the question has. At no time add another problem as you say.
  • ParisaN
    ParisaN about 6 years
    @Learning. It was better that write: frame.getContentPane().setBackground(Color.PINK);
  • Ahm23
    Ahm23 about 5 years
    Thanks for this great solution. It seems that the "C" in Color is case-sensitive.