SDSU CS 596 Java Programming
Fall Semester, 1998
Layouts
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 21-Dec-98

Contents of Doc 30, Layouts


Reference:


Graphic Java 1.2 Volume I: AWT 3 rd Edition, Geary, Chapters 10 (pp. 327-393),


Doc 30, Layouts Slide # 2

Layouts


Need to specify where items will appear in a window that changes size

Layouts provide a flexible way to place items in a window without specifying coordinates

Layouts determine place components will be seen on the screen

A component can be:

ButtonLabelScrollbar
CanvasListTextArea
CheckboxPanelTextField


Listen Here!Q-nov24 3mins, S-nov25 3mins Doc 30, Layouts Slide # 3
About LayoutsBorderLayout

Divides its components into regions



CardLayout

CardLayout contains cards
Each card contains one component
One card can be shown at a time

FlowLayout

Displays components left to right, top to bottom

GridLayout

Displays components in a grid of rows and columns

GridBagLayout

You can do almost anything with this once you understand it

Listen Here!S-nov25 27secs Doc 30, Layouts Slide # 4
Types Of LayoutsLayoutManager Interface
Basic LayoutManager

All Layouts implement this interface

Methods

These methods are used by the container classes. In general, your code does not use these methods.

addLayoutComponent(String, Component)
Adds the specified component with the specified name to the layout.
layoutContainer(Container) 
Lays out the container in the specified panel.
minimumLayoutSize(Container)
Calculates the minimum size dimensions for the specified panel given the components in the specified parent container.
preferredLayoutSize(Container) 
Calculates the preferred size dimensions for the specified panel given the components in the specified parent container.
removeLayoutComponent(Component) 
Removes the specified component from the layout.


Listen Here!Q-nov24 2mins, S-nov25 1min Doc 30, Layouts Slide # 5
LayoutManager2
Interface for layouts with constraints.
Sub-interface of LayoutManager

Methods

In general, your code does not use these methods.
addLayoutComponent(Component, Object)
Adds the specified component to the layout, using the specified constraint object.
getLayoutAlignmentX(Container)
Returns the alignment along the x axis.
getLayoutAlignmentY(Container)
Returns the alignment along the y axis.
invalidateLayout(Container)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
maximumLayoutSize(Container)
Returns the maximum size of this component.


Layout Manager
Implements
Constraints
BorderLayout
LayoutManager2
Compass point string
CardLayout
LayoutManager2
Card name string
FlowLayout
LayoutManager
none
GridBagLayout
LayoutManager2
GridBagConstraints
GridLayout
LayoutManager
none


Doc 30, Layouts Slide # 6
Preferred/Minimum Sizes

Components have a preferred size and a minimum size

BorderLayout
North, South respect preferred height, ignores preferred width
East, West respect preferred width, ignores preferred height
Center ignores preferred height and preferred width

CardLayout ignores preferred height and preferred width

FlowLayout respects preferred height and preferred width

GridLayout ignores preferred height and preferred width

GridBagLayout varies on GridBagConstrants for component

Changing Sizes

If a component changes its size, the window has to be informed. The component should be marked as "dirty" with the invalidate() method. The window's validate() method then must be called. An example is shown starting on slide 11. The above also needs to be done if you wish to change the size of the window in your code.

Doc 30, Layouts Slide # 7

FlowLayout

Constructors
FlowLayout()
Constructs a new Flow Layout with a centered alignment.
FlowLayout( int alignment )
Constructs a new Flow Layout with the specified alignment.
FlowLayout(int alignment , int horizontalGap, int verticalGap )
Constructs a new Flow Layout with the specified alignment and gap values.


Constants for Alignment

CENTER LEFT RIGHT

Center is default


Methods
addLayoutComponent(String, Component) 
getAlignment() 
getHgap() 
getVgap() 
layoutContainer(Container) 
minimumLayoutSize(Container) 
preferredLayoutSize(Container) 
removeLayoutComponent(Component) 
setAlignment(int) 
setHgap(int) 
setVgap(int) 
toString()

Listen Here!Q-nov24 38secs Doc 30, Layouts Slide # 8
How A FlowLayout Works
A simple FlowLayout example.

import java.awt.*;
class  FlowExample  extends Frame  {
   
   public FlowExample( int  width, int height ) {
      setTitle( "Flow Example" );
      setSize( width, height );
      setLayout( new FlowLayout( FlowLayout.LEFT) );
      
      for ( int label = 1; label < 10; label++ )
         add( new Button( String.valueOf( label ) ) );
      show();
   }
   public  static  void  main( String  args[] ) {
      new  FlowExample( 175, 100 );
      new  FlowExample( 175, 100 );
   }
}

Listen Here!Q-nov24 56secs, S-nov25 1min Doc 30, Layouts Slide # 9

Alignment Examples

This example shows the different alignments in a FlowLayout.

import java.awt.*;
class  AlignmentExample  extends Frame  {
   
   public AlignmentExample( int width, int height, 
                     String title, int alignment ) {
      setTitle( title );
      setSize( width, height );
      setLayout( new FlowLayout( alignment) );
      
      add( new Button( "one") );
      add( new Button( "two") );
      show();
   }
   public  static  void  main( String  args[] ) {
      new AlignmentExample( 150, 50, "Left", FlowLayout.LEFT);
      new AlignmentExample( 150, 50, "Right", FlowLayout.RIGHT);
      new AlignmentExample( 150, 50, "Center", FlowLayout.CENTER);
   }
}

Listen Here!Q-nov24 1min, S-nov25 1min Doc 30, Layouts Slide # 10

Gap Example


class  GapExample  extends Frame  {
   
   public GapExample( int  width, int height, String title,
                  int HorizontalGap, int VerticalGap ) {
      setTitle( title );
      setSize( width, height );
      setLayout( new FlowLayout( FlowLayout.LEFT, 
                           HorizontalGap,VerticalGap) );
      
      for ( int label = 1; label < 10; label++ )
         add( new Button( String.valueOf( label ) ) );
      show();
   }
   public  static  void  main( String  args[] ) {
      new  GapExample( 175, 100, "Small Gap", 2, 2 );
      new  GapExample( 175, 100, "Large Gap", 10, 20 );
   }
}


Listen Here!Q-nov24 56secs, S-nov25 2mins Doc 30, Layouts Slide # 11

Changing the Gap

This example shows how to change the gap on the fly. The next slide shows the changing of the gap.

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class  GapChangeExample  extends Frame  {
   Button large = new Button( "Large Gap" );
   Button small = new Button( "Small Gap" );
   
   public GapChangeExample( int  width, int height ) {
      setTitle( "Normal" );
      setSize( width, height );
      setLayout( new FlowLayout( FlowLayout.LEFT ) );
      add( large );
      add( small );
      
      GapListener aListener = new GapListener();
      for ( int label = 1; label < 10; label++ )
         {
         Button aButton = new Button( String.valueOf( label ) );
         add( aButton );
         aButton.addActionListener( aListener );
         }
      large.addActionListener( aListener );
      small.addActionListener( aListener );
      show();
   }
   public  static  void  main( String  args[] ) {
      new  GapChangeExample( 175, 100);
   }

Listen Here!Q-nov24 5mins, S-nov25 11mins Doc 30, Layouts Slide # 12
Changing the Gap
This is the important slide of the example. It shows how to change the gap. Once that is done one also has to mark the layout as invalidated and then tell the window to validate itself. If this is not done, the change will not be seen in the window.
   class GapListener implements ActionListener
      {
      public void actionPerformed( ActionEvent event ) 
         {
         Button selectedButton = (Button) event.getSource();
         int newGap;
         if ( selectedButton == small )
            {
            newGap = 1;
            GapChangeExample.this.setTitle( "Small");
            }
         else if ( selectedButton == large )
            {
            newGap = 20;
            GapChangeExample.this.setTitle( "Large");
            }
         else
            {
            newGap = 5;
            GapChangeExample.this.setTitle( "Middle");
            }
         FlowLayout myLayout = 
            (FlowLayout) GapChangeExample.this.getLayout();
         myLayout.setHgap( newGap );
         myLayout.setVgap( newGap );
         GapChangeExample.this.invalidate();
         GapChangeExample.this.validate();
         }
      }
}

Listen Here!S-nov25 55secs Doc 30, Layouts Slide # 13
Changing the Gap
Here are the different gaps from the example.






Listen Here!Q-nov24 1min, S-nov25 49secs Doc 30, Layouts Slide # 14

GridLayout

Constructors
GridLayout(int, int)
Creates a grid layout with the specified rows and columns.

GridLayout( int rows, cols, horizontalGap, verticalGap )
Creates a grid layout with the specified rows, columns, horizontal gap, and vertical gap.

Methods
addLayoutComponent(String,Component)
layoutContainer(Container)
minimumLayoutSize(Container)
preferredLayoutSize(Container)
removeLayoutComponent(Component)
toString()
A layout manager for a container that lays out grids

Listen Here!S-nov25 3mins Doc 30, Layouts Slide # 15
Grid Example
A simple grid example.

import java.awt.*;
class  GridLayoutExample  extends Frame  {
   
   public GridLayoutExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Grid Example" );
      setSize( widthInPixels, heightInPixels );
      int numberOfRows = 4;
      int numberOfColumns = 3;
      setLayout( new GridLayout( numberOfRows,
                            numberOfColumns ) );
      
      for ( int label = 1; label < 13; label++ )
         add( new Button( String.valueOf( label ) ) );
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  GridLayoutExample( 175, 100 );
   }
}





Doc 30, Layouts Slide # 16

BorderLayout


addLayoutComponent(String,Component)
layoutContainer(Container)
minimumLayoutSize(Container)
preferredLayoutSize(Container)
removeLayoutComponent(Component)
toString()


The "North", "South", "East" and "West" components get placed and sized according to their preferred sizes and the constraints of the container's size.

The "Center" component will get any space left over.

The default layout for a frame is BorderLayout.

Doc 30, Layouts Slide # 17
BorderLayout

import java.awt.*;
class  BorderLayoutExample  extends Frame  {
   
   public BorderLayoutExample( int  widthInPixels, 
                           int heightInPixels ) {
      setTitle( "BorderLayout Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new BorderLayout() );
      
      add(  new Button( "North" ), BorderLayout.NORTH );
      add(  new Button( "Center" ), BorderLayout.CENTER );
      add(  new Scrollbar( Scrollbar.VERTICAL ), BorderLayout.EAST );
      add(  new Scrollbar( Scrollbar.HORIZONTAL ), BorderLayout.SOUTH );
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  BorderLayoutExample( 175, 100 );
   }
}


Doc 30, Layouts Slide # 18

CardLayout

Methods
addLayoutComponent(String,Component)
first(Container)
last(Container)
layoutContainer(Container)
minimumLayoutSize(Container)
next(Container)
preferredLayoutSize(Container)
previous(Container)
removeLayoutComponent(Component)
show(Container,String)
toString()


A layout manager for a container that contains several 'cards'. Only one card is visible at a time, allowing you to flip through the cards.

Listen Here!Q-nov24 6mins, S-nov25 3mins Doc 30, Layouts Slide # 19
Example
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class  CardLayoutExample  extends Frame  {
   CardLayout threeCards;
   Panel deck;
         
   public CardLayoutExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "CardLayoutExample Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new BorderLayout() );
      
      threeCards = new CardLayout();
      deck = new Panel();
      deck.setLayout( threeCards );
      deck.add( "Ace", new Button( "Ace" ) );
      deck.add( "King", new Button( "King" ) );
      deck.add( "Queen", new Button( "Queen" ) );

      add( deck, BorderLayout.CENTER );
      
      Button next = new Button( "Next" );
      next.addActionListener( new NextListener() );
      
      add( next, BorderLayout.NORTH );
      show();
   }
      
   public  static  void  main( String  args[] ) {
      new  CardLayoutExample(200, 200);
   }
   
   class NextListener implements ActionListener {
      public void actionPerformed( ActionEvent buttonPressed ) {
         threeCards.next( deck );
      }
   }
}


Listen Here!Q-dec3 4mins Doc 30, Layouts Slide # 20
GridBagConstrants

gridx, gridy
Column and row positions of the upper left hand corner of the component to be added

gridwidth, gridheight
Number of columns and rows the component will occupy
REMAINDER
RELATIVE
fill
Determines if component fills the entire area
HORIZONTAL
VERTICAL
NONE
BOTH

anchor
If the component does not fill the entire space, anchor indicates where if will be placed

CENTERNORTHEASTSOUTHEAST
EASTNORTHWESTSOUTHWEST
NORTHSOUTHWEST
insets
Margin around the outside of a component

ipadx, ipady
Added to the minimum size of the component

weightx, weighty
How much of available space should the component take


Listen Here!Q-dec3 6mins Doc 30, Layouts Slide # 21

Fill Example

class  GridBagExample  extends Frame  {
   public GridBagExample( int  width, int height ) {
      setTitle( "Grid Bag" );
      setSize( width, height );
      GridBagLayout aLayout = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      setLayout( aLayout );
      
      constraints.gridx = 0;      // Start column
      constraints.gridy = 0;      // Start row
      
      constraints.gridwidth = 2;   // Num. of columns wide
      constraints.gridheight = 1;   // Num. of rows high
      constraints.weighty = 100;
      constraints.weightx = 100;
      
      constraints.anchor = GridBagConstraints.CENTER;
      constraints.fill = GridBagConstraints.NONE;
      
      Button none = new Button( "none" );
      aLayout.setConstraints( none, constraints );
      
      constraints.gridy = 1;
      constraints.fill = GridBagConstraints.HORIZONTAL;
      Button horz = new Button( "horz" );
      aLayout.setConstraints( horz, constraints );
      constraints.gridy = 2;
      constraints.fill = GridBagConstraints.BOTH;
      Button both = new Button( "both" );
      aLayout.setConstraints( both, constraints );
      constraints.gridy = 3;
      constraints.fill = GridBagConstraints.VERTICAL;
      Button vert = new Button( "vert" );
      aLayout.setConstraints( vert, constraints );
      add( none );      add( both );
      add( horz );      add( vert );
      show();
   }
}

Listen Here!Q-dec3 4mins Doc 30, Layouts Slide # 22
Fill Example



Doc 30, Layouts Slide # 23

Anchor Example


class  GridBagExample  extends Frame  {
   public GridBagExample( int  width, int height ) {
      setTitle( "Grid Bag" );
      setSize( width, height );
      GridBagLayout aLayout = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      setLayout( aLayout );
      
      constraints.gridx = 0;      // Start column
      constraints.gridy = 0;      // Start row
      
      constraints.gridwidth = 1;   // Num. of columns wide
      constraints.gridheight = 1;   // Num. rows high
      constraints.weighty = 100;
      constraints.weightx = 100;
      
      constraints.anchor = GridBagConstraints.CENTER;
      constraints.fill = GridBagConstraints.NONE;
      
      Button center = new Button( "center" );
      aLayout.setConstraints( center, constraints );
      
      constraints.gridx = 1;
      constraints.anchor = GridBagConstraints.WEST;
      Button west = new Button( "west" );
      aLayout.setConstraints( west, constraints );
      constraints.gridx = 2;
      constraints.anchor = GridBagConstraints.NORTHWEST;
      Button nwest = new Button( "nwest" );
      aLayout.setConstraints( nwest, constraints );
      constraints.gridx = 3;
      constraints.anchor = GridBagConstraints.NORTHEAST;
      Button neast = new Button( "neast" );
      aLayout.setConstraints( neast, constraints );
      add( center );      add( nwest );
      add( west );      add( neast );
      show();
   }
}

Doc 30, Layouts Slide # 24
Anchor Example



Doc 30, Layouts Slide # 25

Inset Example


class GridBagExample extends Frame {
   public GridBagExample( int  width, int height ) {
      setTitle( "Insets" );
      setSize( width, height );
      GridBagLayout aLayout = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      setLayout( aLayout );
      
      constraints.gridwidth = 1;   // Num. of columns wide
      constraints.gridheight = 1;   // Num. rows high
      int top = 10;            int bottom = 20;
      int left = 12;            int right = 0;
      
      constraints.insets = new Insets( top, left , bottom, right );
      
      constraints.fill = GridBagConstraints.BOTH;
      constraints.weighty = 100;
      constraints.weightx = 100;
      constraints.gridx = 2;
      constraints.gridy = 0;
      Button one = new Button( "one" );
      aLayout.setConstraints( one, constraints );
      
      constraints.gridx = 1;
      Button two = new Button( "two" );
      aLayout.setConstraints( two, constraints );
      constraints.gridx = 0;
      Button three = new Button( "three" );
      aLayout.setConstraints( three, constraints );
      add( one );         add( two );
      add( three );
      show();
   }
}

Doc 30, Layouts Slide # 26
Insets Example

      int top = 10;            int bottom = 20;
      int left = 12;            int right = 0;
      
      constraints.insets = new Insets( top, left , bottom, right );

Doc 30, Layouts Slide # 27

Relative/Remainder Example


Button1, Button2, Button3: weightx=1.0
Button4: weightx=1.0, gridwidth=GridBagConstraints.REMAINDER
Button5: gridwidth=GridBagConstraints.REMAINDER
Button6: gridwidth=GridBagConstraints.RELATIVE
Button7: gridwidth=GridBagConstraints.REMAINDER
Button8: gridheight=2, weighty=1.0,
Button9, Button 10: gridwidth=GridBagConstraints.REMAINDER


Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.

visitors since 24-Nov-98