Select Page

How to change the color of the background of a JFrame content pane

by | May 27, 2023 | JFrame, Swing | 0 comments

The JFrame has a content pane. When you add an object to a JFrame object, you are actually adding it to the content pane of the JFrame.

The content pane is a container the is part of every JFrame object. You cannot see content pane. It does not have a border but any component that is to be displayed in a JFrame must be added to its content pane.

A panel is also a container that can hold GUI components. Panels cannot be displayed by themselves unlike JFrame objects which can be displayed by themselves.

Panels are used to hold and organize collections of related components. The JPanel class is used to create panels.

When you create a JPanel object and add it to the JFrame such that it completely fills the content of the JFrame object, changing the color of the panel may look like the color of the content pane of the JFrame is changed. This is not so.

To change the color of the content pane of JFrame object, we call the getContentPane() method first to refer to the content pane of the the JFrame before setting the color.

Program to change the color of the content pane of the JFrame

Output

changeColor

Program to change both the color of the content pane of JFrame and the panel

Output

changeColorPanelAndPane
changeColorPanelAndPane2