Create a Colored Panel

Learn how to create a colored panel with some of Java's predefined colors.

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.

  1. Remove the code that created anotherLabel and add it to the window.
  2. Create a new JPanel object called centerPanel, initialized by calling JPanel's constructor.
  3. Set the background color of centerPanel to blue using Color's BLUE variable and JPanel’s setBackground() method.
  4. Add centerPanel to the center of the window using JFrame's add() method and BorderLayout's CENTER 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.

  1. In initGUI(), create a JPanel object called leftPanel.
  2. Set the color of leftPanel to red using JPanel’s setBackground() method and Color’s RED variable.
  3. Add leftPanel to the left edge of the window using JFrame's add() method and BorderLayout's LINE_START variable.
  4. Create a JPanel object called rightPanel.
  5. Set the color of rightPanel to green using JPanel’s setBackground() method and Color’s GREEN variable.
  6. Add rightPanel to the right edge of the window using JFrame's add() method and BorderLayout's LINE_END variable.
  7. Create a JPanel object called bottomPanel.
  8. Set the color of bottomPanel to yellow using JPanel's setBackground() method and Color's YELLOW variable.
  9. Add bottomPanel to the bottom of the window using JFrame's add() method and BorderLayout's PAGE_END variable.

Get hands-on with 1200+ tech skills courses.