Draw Smiley Face Java Nested Panels


Draw Smiley Face Java Nested Panels

2. Nested Panels

For a more complex arrangement of components, the panels can be nested. By setting layout for each panel separately, the required layout is achieved. The default layout for Panel is FlowLayout.

The concept of panels and a simple program on panels is available at " Java AWT Panels".

import java.awt.*;
public class NestedPanels extends Frame
{
  public NestedPanels()
  {
    Panel mainPanel = new Panel();
    Panel leftPanel = new Panel();
    Panel rightPanel = new Panel();
                                 // setting layouts as per requirements
    mainPanel.setLayout(new GridLayout(1, 2, 20, 0));
    rightPanel.setLayout(new GridLayout(1, 2, 10, 0));
                                // colors to know the space occupied by each panel
    mainPanel.setBackground(Color.yellow);
    leftPanel.setBackground(Color.pink);
    rightPanel.setBackground(Color.magenta);
                              // populating panels
    leftPanel.add(new Button("Button 1"));
    leftPanel.add(new Button("Button 2"));

    rightPanel.add(new Button("Button 3"));
    rightPanel.add(new Button("Button 4"));
                              // adding left and right panels to main panel
    mainPanel.add(leftPanel);
    mainPanel.add(rightPanel);
                             // adding main panel to frame
    add(mainPanel, "North");

    setSize(400, 200);
    setVisible(true);
  }
  public static void main(String args[])
  {
    new NestedPanels();
  }
}

Thee panels mainPanel, leftPanel and rightPanel are created. leftPanel and rightPanel are added to mainPanel.

mainPanel.setLayout(new GridLayout(1, 2, 20, 0));
rightPanel.setLayout(new GridLayout(1, 2, 10, 0));

mainPanel and rightPanel are set to GridLayout with properties 1 row, 2 columns and 20 or 10 horizontal gap and 0 vertical gap. Colors are set for each panel to know their existence on the frame and the space taken by each.

mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
add(mainPanel, "North");

The two child panels leftPanel and rightPanel are added to mainPanel set with GridLayout earlier. The mainPanel is added to frame on north side.

The affect of all these panels is the following layout arrangement.

The yellow color shows the existence of main panel, the pink and magenta colors indicate left panel and righ panel.

The layouts of the three panels can be changed as follows to get different layout plan.

mainPanel.setLayout(new GridLayout(1,2, 20, 0));
leftPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
rightPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

Leave a Comment

Your email address will not be published.