Back to the home page of this site  

Layout Demonstration

The Layouts Applet will appear in a JDK 1.1 compliant browser



The 1.1 Exam only asks you to understand three LayoutManagers,

The Java2 exam may contain questions about the GridBagLayout manager. Applets default to FlowLayout and applications default to a BorderLayout.

This applet shows the effect of changing the layout manager on an applet. The Layout Manager is set to BorderLayout when the Applet Starts. Clicking the Flow button shows how the FlowLayout manager allows each button to be its preferred size (ie tall and wide enough to contain its label) and and spreads the buttons starting from the top left.


The the two GridLayout Options show how the GridLayout forces the components to fit exactly into the grid. I have not included a BorderLayout button as once the applet has started, re-setting back to BorderLayout seems to have no effect. Another peculiarity BorderLayout is that if you add multiple components to a BorderLayout container without specifying a coordinate (North, South, etc) each component will be added on top of the last one in the Centre. This is generally not what you would want.

  //Source code to the applet
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  
  public class LayTest extends Applet implements ActionListener{
  
                Button btnGrid = new Button("GridLayout(2,2)");
                Button btnGrid2 = new Button("GridLayout(3,3)");
                Button btnFlow = new Button("Flow");
  
        public  void init(){
                setLayout(new BorderLayout());
                amethod();
                }
                public void amethod(){
  
                btnGrid.addActionListener(this);
                btnGrid2.addActionListener(this);
                btnFlow.addActionListener(this);
  
                add(btnGrid,"North");
                add(btnGrid2,"East");
                add(btnFlow,"South");
                }
                public void actionPerformed(ActionEvent evt) {
                       String arg =evt.getActionCommand();
                        if(arg.equals("GridLayout(2,2)"))
                        {
                          setLayout(new GridLayout(2,2));
                          validate();
                        }
  
                       if(arg.equals("GridLayout(3,3)")){
                            System.out.println(arg);
                            setLayout(new GridLayout(3,3));
  
                             validate();
                          }
  
                      if(arg.equals("Flow")){
                          System.out.println(arg);
                          setLayout(new FlowLayout());
                          validate();
  
                   }
  
          }
  }