Create a Colored Panel
Learn how to create a colored panel with some of Java's predefined colors.
We'll cover the following
Like a label, a panel is a component and may be added to any of the areas of BorderLayout
.
Adding a colored panel
Add a colored panel to the window.
- Remove the code that created
anotherLabel
and add it to the window. - Create a new
JPanel
object calledcenterPanel
, initialized by callingJPanel
's constructor. - Set the background color of
centerPanel
to blue usingColor
'sBLUE
variable andJPanel
’ssetBackground()
method. - Add
centerPanel
to the center of the window usingJFrame
'sadd()
method andBorderLayout
'sCENTER
variable.
...
private void initGUI() {
...
titleLabel.setText("Guess My Color");
add(titleLabel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.BLUE);
add(centerPanel, BorderLayout.CENTER);
}
...
Modify the code playground given at the bottom of the lesson and click the run button to display a blue bar below the title.
Using all of BorderLayout
's areas
See how the other areas of the BorderLayout
will be arranged by adding a colored panel to each of BorderLayout
's areas.
- In
initGUI()
, create aJPanel
object calledleftPanel
. - Set the color of
leftPanel
to red using JPanel’ssetBackground()
method and Color’sRED
variable. - Add
leftPanel
to the left edge of the window usingJFrame
'sadd()
method andBorderLayout
'sLINE_START
variable. - Create a
JPanel
object calledrightPanel
. - Set the color of
rightPanel
to green using JPanel’ssetBackground()
method and Color’sGREEN
variable. - Add
rightPanel
to the right edge of the window usingJFrame
'sadd()
method andBorderLayout
'sLINE_END
variable. - Create a
JPanel
object calledbottomPanel
. - Set the color of
bottomPanel
to yellow usingJPanel
'ssetBackground()
method andColor
'sYELLOW
variable. - Add
bottomPanel
to the bottom of the window usingJFrame
'sadd()
method andBorderLayout
'sPAGE_END
variable.
Get hands-on with 1200+ tech skills courses.