Java: JPanel - Container
Description.
A JPanel is an empty area that can be used either to
- Layout other components, including other panels (see below).
- 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));
p.setBackground(Color.blue);
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).
- Add components
- Use
add(...)
to add components to a panel. For example,
p.add(plusButton, BorderLayout.NORTH);
p.add(minusButton, BorderLayout.SOUTH);
Constructors
The most constructor for a panel uses no parameters.
This creates a panel with the default layout, BorderLayout.
Call setLayout
if you want 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 with BoxLayout, so using 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
Example
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.