Add Multiple Panels, Set Size, and Change Text's Color

Learn how to add multiple panels to one panel, set panel size, and change the color of text displayed on any component.

A panel is a container component. A container component can hold more than one component. They’re often a combination of labels, buttons, input fields, and other components.

When a window is packed, all of its components are reduced to their preferred size. You can change the component’s preferred size with a new dimension, which includes width and height.

Adding two panels to one panel

Guess My Color will need two panels to show the sample color and target color. Other methods will use these panels, so they should be defined as instance variables.

  1. Create private JPanel instance variables called samplePanel and targetPanel, initialized by calling the JPanel constructor.
...
private JPanel samplePanel = new JPanel();
private JPanel targetPanel = new JPanel();
public GuessMyColor() {
     ...

Now, add the two panels to the center of the window.

  1. In initGUI(), after adding centerPanel to the window, set the color of samplePanel to black using JPanel’s setBackground() method with Color’s BLACK variable.
  2. Add samplePanel to centerPanel using JPanel’s add() method with only the Component parameter value.
  3. Set the color of targetPanel to cyan using JPanel’s setBackground() method with Color’s CYAN variable.
  4. Add targetPanel to centerPanel using JPanel’s add() method with only the Component parameter value.
...
    public void initGUI() {
    ...
    JPanel centerPanel = new JPanel(); 
    centerPanel.setBackground(Color.BLUE); 
    add(centerPanel, BorderLayout.CENTER);
    samplePanel.setBackground(____________);
    centerPanel.add(samplePanel);
    targetPanel.setBackground(____________); 
    centerPanel.add(__________________);
    JPanel leftPanel = new JPanel();
    ...

Get hands-on with 1200+ tech skills courses.