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

    JFrame mainFrame = new JFrame();
    mainFrame.setSize(100, 100);
    mainFrame.setBackground(Color.CYAN);
    mainFrame.setVisible(true);

My intent is to create a window with a cyan background. What is wrong with this? My window doesn't get cyan, as I'd expect!

Also, could anyone point out why I seem to have all the colors in duplicate (there's a Color.CYAN and a Color.cyan). Is there any difference at all between the two? Maybe the older one was a constant from before there were enums in Java and the second one is from the Enum?

Thanks


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:

  • How to Make Frames - information on general about how to make Frames.

  • How to Use Root Panes - more specific information about panes, including an illustration of how the different panes relate to each other.

  • Using Top-Level Containers

This should work:

JFrame mainFrame = new JFrame();
mainFrame.setSize(100, 100);
mainFrame.getContentPane().setBackground(Color.CYAN);
mainFrame.setVisible(true);

You want to set the color of the JFrame's content pane.

Other than name there's no difference between the upper and camel case color constants.