Home Java Java-tips GUI Containers 30panels JPanel - Container

Ask Questions?

View Latest Questions



JPanel - Container
Posted on: July 24, 2006 at 12:00 AM
You will learn the JPanel.

Java: JPanel - Container


Learn how to use the JPanel Container in a Swing application.


Swing comes with many components. The JPanel is one of he Swing components which can be used to create GUI in a swing based application.


In this example code you will learn many methods of JPanel class.


Description. A JPanel is an empty area that can be used either to


  1. Layout other components, including other panels. See below.
  2. Draw graphics on. See JPanel - Drawing Area.


Use a JPanel to layout other components

Declare and create the JPanel
For example,
JPanel p = new JPanel();
Set the layout and other characteristics
See Layouts. For example,
   p.setLayout(new BorderLayout());
   p.setPreferredSize(new Dimension(200, 100));

You may want to set these characteristics in the constructor of a new class that extends JPanel. The default layout for a JPanel is FlowLayout, but it is a good idea to explicitly set it to avoid any problems with future changes in the default (as happened in the change from Java 1.1 to 1.2). To add to the confusion BorderLayout is the default layout for the JPanel that is the default content pane of a JFrame. It's really clearer to just set it each time.

Add components
Use add(...) to add components to a panel. For example,
   p.add(plusButton, BorderLayout.NORTH);
   p.add(minusButton, BorderLayout.SOUTH);


The most common JPanel constructor has no parameters. This creates a panel with the default layout (FlowLayout). Call setLayout() to change the layout.

JPanel p = new JPanel();
p.setLayout(new FlowLayout());

You can optionally specify the layout in the JPanel constructor call.

JPanel p = new JPanel(new FlowLayout());

However, this doesn't work with BoxLayout, so calling setLayout(...) is still the preferred style of many programmers.

Common methods

p.setLayout(LayoutManager layout);
p.setPreferredSize(new Dimension(int width, int height));
p.setBackground(Color c);
p.add(some component);
w = p.getWidth();  // Used for graphics, not components
h = p.getHeight();  // Used for graphics, not components


JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 3));  // 4 rows and three columns
JButton bx = new JButton("Top left");
p.add(bx);   // bx goes into first grid element.
...          // add more elements to the panel.
Copyleft 2005 Fred Swartz MIT License