Layout Managers

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 13.  Abstract Windows Toolkit


Java's ancestry as an Applet-centric language manifests itself in the way that screen layout is managed. Instead of providing the programmer with method calls to produce an exact size and component layout, the Java language provides you with layout managers. These managers enable you to express opinions about where each object will be placed on the screen, but not the exact coordinates that will be used.

The reason for this indirection is to accommodate browser-based GUIs. If your GUI is going to be downloaded over the Internet and run in a browser, you have no idea of the screen resolution, window size, or even the browser brand that will run it. You must assume that (almost) every possible configuration must be supported. This is very hard to do with method calls and switch statements.

To make things easier, the Java designers have provided you with a set of layout managers that can be used either alone or in combination to provide you with the look that you want.

The layout managers provided by the java.awt package are not made obsolete by Swing. Swing applications can use all the layout managers mentioned in this chapter.

The layout managers that are available for you to choose from are the BorderLayout, FlowLayout, CardLayout, GridLayout, and the GridBagLayout.

We will look at each of these in turn and provide a summary of the advantages of each.

The BorderLayout Manager

The BorderLayout class is fairly easy to use. Normally, you create Panel objects and place GUI objects such as buttons and text fields on them. Next, you place these panels in one of the regions on the layout. When you display the window, each panel will appear in the region where it was assigned. Listing 13.17 shows a BorderLayout example.

Listing 13.17 The TestBorderLayout.java File
 /*   * TestBorderLayout.java   *   * Created on July 30, 2002, 11:35 AM   */  package com.samspublishing.jpp.ch13;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestBorderLayout extends Frame  {     TextField tfNorth;     TextField tfCenter;     TextField tfSouth;     TextField tfEast;     TextField tfWest;      /** Creates new TestBorderLayout */     public TestBorderLayout()     {        tfNorth = new TextField("North");        tfCenter= new TextField("Center");        tfSouth = new TextField("South");        tfEast = new TextField("East");        tfWest = new TextField("West");        Panel pNorth = new Panel();        pNorth.add(tfNorth);         Panel pCenter = new Panel();        pCenter.setBackground(Color.darkGray);        pCenter.add(tfCenter);        Panel pSouth = new Panel();        pSouth.add(tfSouth);        Panel pEast = new Panel();        pEast.setBackground(Color.gray);        pEast.add(tfEast);        Panel pWest = new Panel();        pWest.setBackground(Color.gray);        pWest.add(tfWest);        add(pNorth, BorderLayout.NORTH);        add(pCenter, BorderLayout.CENTER);        add(pSouth, BorderLayout.SOUTH);        add(pEast, BorderLayout.EAST);        add(pWest, BorderLayout.WEST);        addWindowListener(new WinCloser());        setTitle("Using a BorderLayout");        setBounds( 100, 100, 300, 300);        setVisible(true);     }     public static void main(String[] args)     {        TestBorderLayout tbl = new TestBorderLayout();     }  }  class WinCloser extends WindowAdapter  {     public void windowClosing(WindowEvent e)     {        System.exit(0);     }  } 

The Frame class defaults to a BorderLayout by default, so there is no need to specify it directly. We declare five text fields to place on the panels.

 tfNorth = new TextField("North");  tfCenter= new TextField("Center");  tfSouth = new TextField("South");  tfEast = new TextField("East");  tfWest = new TextField("West"); 

We create a panel for each text field so that the button will have a container. If you place objects directly on the frame, strange sizing can take place.

 Panel pCenter = new Panel(); 

We set a background color to make it clear where the boundary of each region falls.

 pCenter.setBackground(Color.darkGray); 

We add the text field to the panel.

 pCenter.add(tfCenter); 

Finally, we add the panels to the frame specifying a different region for each one.

 add(pNorth, BorderLayout.NORTH);  add(pCenter, BorderLayout.CENTER);  add(pSouth, BorderLayout.SOUTH);  add(pEast, BorderLayout.EAST);  add(pWest, BorderLayout.WEST); 

Running this program produces the result shown in Figure 13.18.

Figure 13.18. The BorderLayout enables you to place objects in five regions.

graphics/13fig18.gif

The panels are colored differently to show where one region begins and another one ends. The BorderLayout class has a mind of its own when it comes to sizing regions. You can only affect its decisions indirectly.

FlowLayout

The simplest layout of all is the FlowLayout layout manager. When a component is placed on the frame, it is placed in the left-most position. Each successive component is placed beside it until no more will fit. In that case, a new row is started and the next component is placed there. Listing 13.18 shows how this works.

Listing 13.18 The TestFlowLayout.java File
 /*   * TestFlowLayout.java   *   * Created on July 30, 2002, 11:35 AM   */  package com.samspublishing.jpp.ch13;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestFlowLayout extends Frame  {     TextField tfFirst;     TextField tfSecond;     TextField tfThird;     TextField tfFourth;     TextField tfFifth;     /** Creates new TestFlowLayout */     public TestFlowLayout()     {        setLayout(new FlowLayout());        tfFirst = new TextField("First");        tfSecond= new TextField("Second");        tfThird = new TextField("Third");        tfForth = new TextField("Fourth");        tfFifth = new TextField("Fifth");        add(tfFirst);        add(tfSecond);        add(tfThird);        add(tfFourth);        add(tfFifth);         addWindowListener(new WinCloser());        setTitle("Using a FlowLayout");        setBounds( 100, 100, 300, 300);        setVisible(true);     }     public static void main(String[] args)     {        TestFlowLayout tfl = new TestFlowLayout();     }   }  class WinCloser extends WindowAdapter  {     public void windowClosing(WindowEvent e)     {        System.exit(0);      }  } 

The only line in this example that is new is the declaration of the layout manager. This is necessary because a Frame's default layout is a BorderLayout, which doesn't provide the desired appearance in this example.

 setLayout(new FlowLayout()); 

After this is declared, the FlowLayoutManager class handles the placement of the components on the screen. Figure 13.19 shows the result of running this.

Figure 13.19. The FlowLayout enables you to place objects in the Frame from left to right with wrapping.

graphics/13fig19.gif

GridBagLayout

The GridBagLayout manager is the most powerful, but the most complicated of the Layout managers to implement. It acts a lot like a spreadsheet program by placing items in different rows and columns. It differs from an ordinary spreadsheet in that it allows the cells to differ in size, one from another.

A special helper class called GridBagConstraints handles the complexity of this layout manager. This class enables the programmer to specify the coordinates, dimensions, spacing, and padding. Listing 13.19 shows an example of this layout manager.

Listing 13.19 The TestGridBagLayout.java File
 /*   * TestGridBagLayout.java   *   * Created on July 30, 2002, 11:35 AM   */  package com.samspublishing.jpp.ch13;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestGridBagLayout extends Frame  {     TextField tfFirst;     TextField tfSecond;     TextField tfThird;     TextField tfFourth;      TextField tfFifth;     GridBagConstraints gbc;     Button saveButton;     Label answerLabel;     /** Creates new GridBagLayout */     public TestGridBagLayout()     {        Insets i = new Insets(0, 0, 0, 0);        saveButton = new Button("Save");        answerLabel = new Label("Answer:");        tfFirst = new TextField("First");        tfSecond= new TextField("Second");        tfThird = new TextField("Third");        tfForth = new TextField("Forth");        tfFifth = new TextField("Fifth");        GridBagLayout gbl = new GridBagLayout();        setLayout(gbl);        gbc = new GridBagConstraints(0,0,1,1,0.0,0.0,                                     GridBagConstraints.EAST,                                      GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(answerLabel, gbc);        gbc = new GridBagConstraints(1,0,1,1,0.0,0.0,                                      GridBagConstraints.WEST,                                     GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(tfFirst, gbc);        gbc = new GridBagConstraints(1,11,1,1,0.0,0.0,                                     GridBagConstraints.WEST,                                     GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(tfSecond, gbc);        gbc = new GridBagConstraints(1,8,1,1,0.0,0.0,                                     GridBagConstraints.WEST,                                     GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(tfThird, gbc);        gbc = new GridBagConstraints(2,0,1,1,0.0,0.0,                                     GridBagConstraints.WEST,                                     GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(tfForth, gbc);         gbc = new GridBagConstraints(2,1,1,1,0.0,0.0,                                     GridBagConstraints.WEST,                                     GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(tfFifth, gbc);        gbc = new GridBagConstraints(8,1,1,1,0.0,0.0,                                     GridBagConstraints.WEST,                                     GridBagConstraints.NONE,                                     i,0,0);        gbl.setConstraints(saveButton, gbc);        add(tfFirst);        add(tfSecond);        add(tfThird);        add(tfFourth);        add(tfFifth);        add(answerLabel);        add(saveButton);        addWindowListener(new WinCloser());        setTitle("Using a GridBagLayout");        setBounds( 100, 100, 300, 300);        setVisible(true);      }     public static void main(String[] args)     {        TestGridBagLayout tgbl = new TestGridBagLayout();     }   }  class WinCloser extends WindowAdapter  {     public void windowClosing(WindowEvent e)     {        System.exit(0);     }  } 

We need an object that we can use to set the formatting options.

 GridBagConstraints gbc; 

Normally, we create a layout manager without giving it a name. In this case, we give it a name that we will use later.

 GridBagLayout gbl = new GridBagLayout(); 

We will set the layout next.

 setLayout(gbl); 

Every object that is to be placed on the frame needs to have its constraints specified. The meaning of each parameter is as follows:

  • gridx The column location

  • gridy The row location

  • gridwidth Width of the cell

  • gridheight Height of the cell

  • weightx How extra row space will be allocated

  • weighty How extra column space will be allocated

  • anchor Where the component is anchored in the cell, as in GridBagConstraints.NORTH.

  • fill Whether and how a component will be stretched

  • insets The space between the component and the edge of the cell.

  • ipadx Padding in the x direction

  • ipady Padding in the y direction

 gbc = new GridBagConstraints(0,0,1,1,0.0,0.0,                               GridBagConstraints.EAST,                               GridBagConstraints.NONE,                               i,0,0);  gbl.setConstraints(answerLabel, gbc); 

Finally, we add each component to the Frame in the same way that we always have.

 add(tfFirst); 

The result of running this example is shown in Figure 13.20.

Figure 13.20. The GridBagLayout enables you to place objects in cells with quite a bit of control over the layout.

graphics/13fig20.gif

Notice that there are no blank columns or rows in the result, even though we specified high row and column numbers for some of the components. If a row or column is empty, it is ignored by the layout manager.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net