Academic Java    Java Tutorial  >  Swing  >  JPanel

JPanel Example

Java JPanel EXAMPLE output This JPanel example shows two JPanels.

JPanel is a subclass of JComponent and therefore instances of it can be added into a container such as a JFrame's content pane. JComponent is a subclass of Container and therefore a JPanel is also a container and can be added into.

In this example labels are added into two different JPanels which are then added into the frame's content pane. The design of a complex user interface can be eased by the use of JPanels, each of which may take advantage of different layout managers, as shown here.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// JPanel Example
import java.awt.*;
import javax.swing.*;

class JPanelExample {

   public static void main(String[] args) {

      JPanel jpanel_0 = new JPanel();
      jpanel_0.setBackground(Color.pink);
      for(int i=0;i<3;++i) jpanel_0.add(new JLabel("label"+i));

      JPanel jpanel_1 = new JPanel(new GridLayout(0,1));
      jpanel_1.setBackground(Color.cyan);
      for(int i=0;i<7;++i) jpanel_1.add(new JLabel("  label"+i+"  "));

      JFrame frame = new JFrame();
      Container cp = frame.getContentPane();
      cp.add(jpanel_0,BorderLayout.WEST);
      cp.add(jpanel_1,BorderLayout.EAST);

      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);

   }
}

9-10 This construction of a pink JPanel gets the default layout manager FlowLayout.

13-14 This construction of a cyan JPanel gets a GridLayout layout manager, with one column and any number of rows.

* JPanel Examples