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
JPanel p = new JPanel();
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). 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(...)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).
setLayout() to change the
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.
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.