PANELS

Java AWT Panels play a very important role in layout management. Panels in combination with layout managers render the desired layout to the programmer.
Following hierarchy gives the place of Panel in AWT API.
java.lang.Object –> java.awt.Component –> java.awt.Container –> java.awt.Panel –> java.applet.Applet
Properties of Java AWT Panels
  1. As you can see from the hierarchy, a panel is both a component and a container as it is a subclass of both Component and Container. As a component it can be added to another container and as a container it can be added with components. Panels work both ways.
  2. The default layout manager for panel is FlowLayout which can be changed as per the requirement of the layout.
  3. It is known as a child window. As a child window, it does not have a border.
  4. Panels can be nested (known as nested panels) for better layout presentation.
Following program illustrates the panels' usage in layout management. In the following program, three buttons are added to the north (top) of the frame and three buttons to the south (bottom) of the frame. Without panels, this arrangement is not possible with mere layout managers.
Example on Java AWT Panels

Java AWT Panels
Output screen of Java AWT Panels
Panel p1 = new Panel();
Panel p2 = new Panel();
Two panels, p1 and p2 are created and set background colors to know the space occupied by them.
p2.setLayout(new GridLayout(1, 3, 20, 0));
The default layout manager for a panel is FlowLayout. The panel p1 default layout manager is not disturbed. But for practice sake, the layout of p2 is changed to GridLayout with 1 row, 3 columns, 20 horizontal gap and 0 vertical gap (as only one row exist).
p1.add(b1); p1.add(b2); p1.add(b3);
Three buttons b1b2 and b3 are added to the panel p1. Similarly, buttons b4b5 and b6 are added to panel p2.
add(p1, “North”);
add(p2, “South”);
Panel p1 is added to the north of the frame and p2 is added to the south. Along with panelp1, three buttons go and stay on the frame on north-side. But on the account of frame only one component p1 exists. Like this, panels can be added to the east and west of the frame also.
Note: For simplicity, the window closing code is not included. For closing this frame, 4 styles exist and you can apply any one to this program to close the frame.

No comments:

Post a Comment