JFrame.setBackground() not working — why? [duplicate]

Why is the windows not cyan as expected?

The issue here is that the area where the contents of the JFrame is being displayed is actually the “content pane”, and not contents of the JFrame itself.

Therefore, the following line:

mainFrame.setBackground(Color.CYAN);

Is changing the color of the JFrame, but that is actually not the part which is immediately visible when the JFrame is displayed.

What is needed is to change the color of what is called the “content pane* (please refer to How to Use Root Panes for an illustration), by changing the above line to the following:

mainFrame.getContentPane().setBackground(Color.CYAN);

Using Frames in Swing could be surprisingly unintuitive at the beginning, so I would strongly recommend taking a look at the resources I’ve listed at the bottom of this answer.

Is there a difference between Color.CYAN and Color.cyan?

No, there is no difference between the two — they are both constants in the Color class which are Color objects themselves. The only difference is in the names of the constants.

The constants with lowercase names were introduced when the Color class was introduced (which appears to be JDK 1.0, as there is no “Since” notation in the Java API Specification for the Color class), and the uppercase names were added later on in JDK 1.4.

Probably the addition of the uppercase named constants were added to make the constant names in the Color class consistent with the Code Conventions for the Java Programming Language which in Section 9: Naming Conventions state that constants should be in all uppercase letters.

Resources

For more information on how to use Frames, the following resources from The Java Tutorials would be of interest:

Leave a Comment