How can we add multiple sub-panels to the main panel in Java?


A JPanel is a subclass of JComponent class and it is an invisible component in Java. The FlowLayout is a default layout for a JPanel. We can add most of the components like buttons, text fields, labels, tables, lists, trees, etc. to a JPanel.

We can also add multiple sub-panels to the main panel using the add() method of Container class.

Syntax

public Component add(Component comp)

Example

import java.awt.*;
import javax.swing.*;
public class MultiPanelTest extends JFrame {
   private JPanel mainPanel, subPanel1, subPanel2;
   public MultiPanelTest() {
      setTitle("MultiPanel Test");
      mainPanel = new JPanel(); // main panel
      mainPanel.setLayout(new GridLayout(3, 1));
      mainPanel.add(new JLabel("Main Panel", SwingConstants.CENTER));
      mainPanel.setBackground(Color.white);
      mainPanel.setBorder(BorderFactory.createLineBorder(Color.black, 1));
      subPanel1 = new JPanel(); // sub-panel 1
      subPanel1.add(new JLabel("Panel One", SwingConstants.CENTER));
      subPanel1.setBackground(Color.red);
      subPanel2 = new JPanel(); // sub-panel 2
      subPanel2.setBackground(Color.blue);
      subPanel2.add(new JLabel("Panel Two", SwingConstants.CENTER));
      mainPanel.add(subPanel1);
      mainPanel.add(subPanel2);
      add(mainPanel);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new MultiPanelTest();
   }
}

Output

Updated on: 03-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements