JPanel in Java Swing

JPanel is a container component in Java Swing that is used to hold and organize other components. It is often used as a building block for creating more complex user interfaces.

JPanel extends the JComponent class and provides methods for managing layout, adding and removing components, painting the panel, and handling events. Some common uses of JPanel include:

  1. Creating a custom panel with a specific layout and adding components to it.
  2. Creating a container for other components that can be added to a frame or another container.
  3. Providing a background color or image for a group of components.

To create a JPanel, we can simply call its default constructor:

JPanel panel = new JPanel();

We can then add components to the panel using the add() method:

panel.add(new JButton("Click me!"));

We can also set the layout manager for the panel using the setLayout() method. For example, to create a panel with a grid layout:

JPanel panel = new JPanel(new GridLayout(2, 2));
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));

You can customize the appearance of the panel by setting its background color or image using the setBackground() method:

panel.setBackground(Color.WHITE);

Let’s see the complete example code mentioned above:

import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JPanelDemo extends JFrame {
    
    public JPanelDemo() {
        setTitle("JPanel Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        
        // Create a new panel with a grid layout
        JPanel panel = new JPanel(new GridLayout(2, 2));
        
        // Add buttons to the panel
        panel.add(new JButton("Button 1"));
        panel.add(new JButton("Button 2"));
        panel.add(new JButton("Button 3"));
        panel.add(new JButton("Button 4"));
        
        // Set the background color of the panel
        panel.setBackground(Color.WHITE);
        
        // Add the panel to the frame
        add(panel);
        
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new JPanelDemo();
    }
}

When we run this code, it will create a window with a panel containing four buttons arranged in a 2×2 grid. The panel’s background color will be set to white.

Output:

JPanel in Java Swing Jpanel demo

Though we set the JPanel background to white, it still does not show in the output because the JButton we’ve added is inside the JPanel.