Tutorial: Various Layout Managers

Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






To visit my site

[HOME] [Consulting] [Design] [Maintenance] [Project] [Testing] [Training] [Turnkey] [Java] [C++] [SQL] [HTML] [JavaScript ]



To contact us

© 2002 - 2009 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following link or send this page to a friend.)
  • <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/LayoutManager/FlowLayout/VariousLayouts_Demo.html">An Introduction to Various Layout Managers </a>
    </table>
    </body>
    </html>
  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III

Objectives

After you finish this tutorial, you will understand:

  • How to create various layout managers such as;
    • FlowLayout
    • FlowLayout with Big Hgap
    • BorderLayout
    • BoxLayout
    • GridBagLayout
    • GridLayout(4,5)
    • GridLayout(1, 6)
    • GridLayout(6, 1)

Introduction to various layout managers

The purpose of this tutorial is to introduce you to the concept of the Various Layout managers by using an example. The CardLayout manager, which implements the LayoutManager2 Interface, will be the primary layout manager. A CardLayout object is a layout manager for a container, such as a panel. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. The ordering of cards is determined by the container's own internal ordering of its component objects. For those who are familiar with stacks, this behavior is similar to a FIFO (First In First Out) stack. In this example, all new items are added to the bottom of the stack, and when the stack is popped, the first item on the stack is popped first.

 

         +---------------+
        /               // 
       /  First Card   ///
      /               ////
     /               /////
    /               //////
   /_______________//////
   /_______________///// <---- new cards added at the bottom
   /_______________////
   /_______________///
   /_______________//
   /_______________/
 
Figure 1: Card Deck


In the above figure, the First Card is the first card placed on the deck and is the first card removed/popped from the deck.

Card template

In the following table, we will show a CardLayout code snippet.

 

/** ************************************************************
 * VariousLayoutsDemo.java demonstrates the basic concept of the 
 * Cardlayout Manager, in addition to other layout managers.
 * 
 ***************************************************************/ 

public class VariousLayoutsDemo extends JFrame
                      implements ActionListener {

   public Card()  {
 
   }

   public void itemStateChanged(ItemEvent evt) {

   }

   public void actionPerformed( ActionEvent e )    {
                  
   }

   public static void main( String args[] )    {
      
   }
} /****************** End of VariousLayoutsDemo class ************************/ 

 
 
Figure 2: VariousLayoutsDemo template


The code you will want place in the Figure 2 template is found in the next section.

VariousLayoutsDemo example code

The code for the VariousLayoutsDemo example is

 
/** ************************************************************
 * VariousLayoutsDemo.java This applet demonstrates how to create
 * various layout managers.
 *  
 * Copyright (c) 2002-2009 Advanced Applications Total Applications Works.
 * (AATAW)  all Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Total Application works nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *
 * 1- FlowLayout
 * 2- FlowLayout with Big Hgap
 * 3- BorderLayout
 * 4- BoxLayout
 * 5- GridBagLayout
 * 6- GridLayout(3,2)
 * 7- GridLayout(1, 6)
 * 8- GridLayout(6, 1)
 *
 *************************************************************/

import java.awt.*;
import java.awt.event.*;
import javax.swing.* ;

/** ************************************************************
 * The VariousLayoutsDemo class applet creates and demonstrates
 * various layout managers. The VariousLayoutsDemo creates a panel
 * that uses BorderLayout as its layout manager with a
 * 1- Panel in the center managed by a CardLayout manager
 *    - Each card in the card layout uses a different layout manager
 *      and contains various number of buttons.
 * 2- "Choice" pop-up menu to the North, and the
 *    - The "Choice" pop-up menu is used to select among these cards.
 * 3- Label in the south.
 *    - The Label reports events as they occur.
 ***************************************************************/
public class VariousLayoutsDemo extends JFrame implements
                             ItemListener, ActionListener {

   private CardLayout cards;  // the layout manager for the center panel

   private JLabel statusLabel;     // a statusLabel shown at the bottom of the applet
   private Container c ;
   private String butNames[] = { "1st Button", " ", "2nd Button", "3rd Button",
                                 "4th Button", " ", "5th Button", "6th Button",
                                 " ", "7th Button" } ;
   private String butNames2[] = { " A Button", "Second Button",
                                  "A Third Button", "A Fourth Button",
                                  "A Fifth Button" } ;
   private String butNames3[] = { "Center Button", "North Button", "South Button",
                                  "East Button", "West Button" } ;
   private String bordNames[] = { BorderLayout.CENTER, BorderLayout.NORTH,
                                  BorderLayout.SOUTH, BorderLayout.EAST,
                                  BorderLayout.WEST } ;
   private String butNames4[] = { "7", "8", "9", "C", "AC" ,
                                  "4", "5", "6", "*", "/" ,
                                  "1", "2", "3", "-", "+",
                                  "+/-", "0", ".", "=", " "  } ;
   private String butNames5[] = { "7", "8", "9", "C", "AC" ,
                                  "4", "5", "6", "*", "/" ,
                                  "1", "2", "3", "-", "+",
                                  "+/-", "0", ".", "=", "SQRT" } ;
   private String butNames6[] = { "7", "8", "9", " ", "C", "AC",
                                  "4", "5", "6", "*", "/" , "M+" ,
                                  "1", "2", "3", "-", "+", "M-" ,
                                  "+/-", "0", ".", "=", "SQRT", "1 / x" } ;

   private String names[] = { "Mahogany", "Walnut", "Cherry" };
   private  int CENTER = 0 ;

   private JPanel cardStack;   // the center panel serves as the deck
   private JPanel flowPanel, flowPanel2, bordPanel, gridPanel, gridPanel2,
                    gridPanel3, hBoxPanel, vBoxPanel, BoxPanel, gridBagPanel ;
   private JTextArea jta  = new JTextArea( "This is TextArea 1", 5, 15 ), 
                     jtx  = new JTextArea(  "This is TextArea 2", 2, 2  ) ;
   private JComboBox cBox ;
   private JTextField tField  = new JTextField( "TextField" );
   private JButton b1, b2, b3 ;
   private GridBagConstraints gbConstraints = new GridBagConstraints() ; 
   private GridBagLayout gBLay = new GridBagLayout() ;

   /** ************************************************************
    * The VariousLayoutsDemo() constructor is used create and 
    * initialize objects in this program. The logic is:
    * 1- Obtain the client area context;
    * 2- Set the background color to blue;
    * 3- Add a label area where event status can be deisplayed
    * 4- Create a Choice pop-up menu;
    *    - Set the Background color to white
    *    - Add an ItemListener to the pop-up menu
    *    - Add a FlowLayout item
    *    - Add a FlowLayout with Big Hgap item
    *    - Add a GridLayout(4,4) item
    *    - Add a GridLayout(4,4) item
    *    - Add a GridLayout(4,6) item
    *    - Add a BoxLayout item
    *    - Add a GridBagLayout item
    * 4- Set up the center panel that will be used as the card deck
    * 5- Set up the center panel to use the BorderLayout manager
    * 6- Create the  various cards
    *    - Create a FlowLayout card
    *    - Create a FlowLayout with Big Hgap card
    *    - Create a GridLayout(4,4) card
    *    - Create a GridLayout(4,4) card
    *    - Create a GridLayout(4,6) card
    *    - Create a BoxLayout card
    *    - Create a GridBagLayout card
    * 7- Add the above cards to the deck - cardStack
    * 8- Set the size
    * 9- Make the frame visiable by using the show() method
    *  
    ***************************************************************/
   public VariousLayoutsDemo() {

      c = getContentPane() ;

      c.setBackground(Color.blue);

      statusLabel = new JLabel("Various Layouts Demo" );  // Set up the mesage
      statusLabel.setBackground(Color.blue);
      statusLabel.setForeground(Color.white);
      statusLabel.setHorizontalAlignment( CENTER );

      Choice panelChoice = new Choice();       // Set up the "Choice" menu
      panelChoice.setBackground( Color.white ) ;
      panelChoice.addItemListener( this ) ;
      panelChoice.add( "FlowLayout" ) ;           // Add in the names of the cards.
      panelChoice.add( "FlowLayout with Big Hgap" ) ;
      panelChoice.add( "BorderLayout" ) ;
      panelChoice.add( "GridLayout(4,5)" ) ;
      panelChoice.add( "GridLayout(4,4)" ) ;
      panelChoice.add( "GridLayout(4,6)" ) ;
      panelChoice.add( "BoxLayout" ) ;
      panelChoice.add( "GridBagLayout" ) ;

          //  Set up the center panel - card deck
      cardStack = new JPanel();
      cardStack.setBackground(Color.white);
      cards = new CardLayout();
      cardStack.setLayout(cards);

          // Setup the BorderLayout for the client context
      c.setLayout(new BorderLayout(3,3));
      c.add(cardStack, BorderLayout.CENTER  );
      c.add(panelChoice, BorderLayout.NORTH  );
      c.add(statusLabel, BorderLayout.SOUTH  );

      /** *****************************************************
       * Set up each "card" in the center panel to have its
       * own layout manager and to contain a variety of buttons.
       *
       * use default FlowLayout for panel
       ** *****************************************************/
      flowPanel = new JPanel() ;
      for (int ii = 0 ; ii < 9 ; ii++ ) {
         JButton b = new JButton( butNames[ ii ] );
         flowPanel.add(b);
         b.addActionListener(this);
      }

      flowPanel2 = new JPanel();
      flowPanel2.setLayout(new FlowLayout( FlowLayout.CENTER,30000,5 ) ) ;
      for (int ii = 0 ; ii < 5 ; ii++ ) {
         JButton b = new JButton( butNames2[ ii ] );
         flowPanel2.add(b);
         b.addActionListener(this);
      }

      bordPanel = new JPanel() ;
      bordPanel.setLayout( new BorderLayout() ) ;
      for (int ii = 0 ; ii < 5 ; ii++ ) {
         JButton b = new JButton( butNames3[ ii ] );
         bordPanel.add(b , bordNames[ ii ] );
         b.addActionListener(this);
      }

      gridPanel = new JPanel();
      gridPanel.setLayout( new GridLayout( 4, 5 ) ) ;
      for (int ii = 0 ; ii < 20 ; ii++ ) {
         JButton b = new JButton( butNames4[ ii ] ) ;
         b.setFont( new Font( "Serif" , Font.BOLD , 24 ) ) ;
         gridPanel.add(b) ;
         b.addActionListener(this) ;
      }


      gridPanel2 = new JPanel();
      gridPanel2.setLayout( new GridLayout( 4, 5 ) );
      for (int ii = 0 ; ii < 20 ; ii++ ) {
         JButton b = new JButton( butNames5[ ii ] ) ;
         b.setFont( new Font( "Serif" , Font.BOLD , 24 ) ) ;
         gridPanel2.add(b) ;
         b.addActionListener(this) ;
      }

      gridPanel3 = new JPanel();
      gridPanel3.setLayout( new GridLayout( 4, 6 ) );
      for (int ii = 0 ; ii < 24 ; ii++ ) {
         JButton b = new JButton( butNames6[ ii ] ) ;
         b.setFont( new Font( "Serif" , Font.BOLD , 24 ) ) ;
         gridPanel3.add(b) ;
         b.addActionListener(this) ;
      }

      gridBagPanel = new JPanel() ;
      gridBagPanel.setLayout( gBLay ) ;

      cBox   = new JComboBox( names );
      buildGridBag() ;

      hBoxPanel = new JPanel() ; 
      hBoxPanel.setLayout( new BoxLayout(hBoxPanel, BoxLayout.X_AXIS ) ) ;
      for(int i = 0; i < 5; i++)
         hBoxPanel.add( new JButton("n_Horiz " + i ) ) ;

      vBoxPanel = new JPanel() ;
      vBoxPanel.setLayout( new BoxLayout(vBoxPanel, BoxLayout.Y_AXIS ) ) ;
      for(int i = 0; i < 5; i++)
         vBoxPanel.add( new JButton("v_Horiz " + i ) ) ; 
      BoxPanel = new JPanel() ;
      BoxPanel.add( hBoxPanel, BorderLayout.SOUTH ) ;;
      BoxPanel.add( vBoxPanel, BorderLayout.WEST ) ;

      cardStack.add( flowPanel,  "FlowLayout" ) ;
      cardStack.add( flowPanel2, "FlowLayout with Big Hgap") ;
      cardStack.add( bordPanel,  "BorderLayout" ) ;
      cardStack.add( gridPanel,  "GridLayout(4,5)" ) ;
      cardStack.add( gridPanel2, "GridLayout(4,4)" ) ;
      cardStack.add( gridPanel3, "GridLayout(4,6)" ) ;
      cardStack.add( BoxPanel  , "BoxLayout" ) ;
      cardStack.add( gridBagPanel , "GridBagLayout"  ) ;

      setSize( 500 , 250 ) ;
      show() ;

   }
   /*********************** end init() ***************************/


   /** ************************************************************
    * The buildGridBag() method does the following:
    * 1- Add a Text area to the panel
    * 2- Add three Buttons to the panel
    * 3- Add combo box to the panel
    * 4- Add text area to the panel
    * 5- Add text field to the panel
    * 
    ***************************************************************/
   public void buildGridBag() {

      
      gbConstraints.fill = GridBagConstraints.BOTH;
      addComponent( jta, 0, 0, 1, 2 );    // Add a JTextArea
       
      b1 = new JButton( butNames[ 0 ] ) ;
      gbConstraints.fill = GridBagConstraints.HORIZONTAL;
      addComponent( b1, 0, 1, 1, 1 );
      b1.addActionListener(this) ;   
   
      b2 = new JButton( butNames[ 2 ] ) ;
      gbConstraints.weightx = 1000;  // can grow wider
      gbConstraints.weighty = 1;     // can grow taller
      gbConstraints.fill = GridBagConstraints.BOTH; 
      addComponent( b2, 1, 1, 1, 1 );
      b2.addActionListener(this) ;   
       
      b3 = new JButton( butNames[ 3 ] ) ;
      gbConstraints.weightx = 0;
      gbConstraints.weighty = 0;    
      addComponent( b3, 1, 2, 2, 2 );
      b3.addActionListener(this) ;   
      
      addComponent( cBox, 2, 1, 3, 1 );    // fill is HORIZONTAL

      addComponent( jtx, 3, 2, 1, 1 );
       
      addComponent( tField, 3, 0, 2, 1 );
   }
   /****************** end of buildGridBag() **********************/

   /** ******************************************************
    * The addComponent() method uses the GridBagConstraints
    * when computing how to layout the various components.
    * 
    *********************************************************/     
   private void addComponent( Component c,
      int row, int column, int width, int height )
   {
      // set gridx and gridy 
      gbConstraints.gridx = column;
      gbConstraints.gridy = row;

      // set gridwidth and gridheight
      gbConstraints.gridwidth = width;   
      gbConstraints.gridheight = height;

      // set constraints
      gBLay.setConstraints( c, gbConstraints );  
      gridBagPanel.add( c );      // add component to the gridBagPanel
   }
   /****************** end of addComponent() **********************/

   /** ************************************************************
    * The actionPerformed() method responds the JButton events.
    * 
    ***************************************************************/
   public void actionPerformed(ActionEvent evt) {
         // A button was pressed.  Report the name
         // of the button by setting the statusLabel text.
      String buttonName = evt.getActionCommand();
      statusLabel.setText("Button \"" + buttonName + "\" was pressed.");
   }
   /****************** end of actionPerformed() **********************/


   /** ************************************************************
    * When a selection is made from the "Choice" popup menu, the
    * following occurs:
    * 1- The card name is displayed in the status label window
    * 
     ***************************************************************/
   public void itemStateChanged(ItemEvent evt) {
      String panelName = (String)evt.getItem() ;
      cards.show(cardStack, panelName) ;
      statusLabel.setText("Panel \"" + panelName + "\" was selected.") ;
   }
   /****************** end itemStateChanged() **********************/

   /** *****************************************************
    * The main() method is the entry point called by Java 
    * when this program is loaded into memory
    * 
    *********************************************************/  
   public static void main( String args[] )
   {
      VariousLayoutsDemo app = new VariousLayoutsDemo();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }


}
/*********************** end class VariousLayoutsDemo *******************/
 
 
Figure 3: VariousLayoutsDemo example code


The code and file used to compile and run this code is found in the next section.

Batch file used to compile and run the VariousLayoutsDemo example code

The following example is the Bat file used to compile and run the VariousLayoutsDemo code.

 
javac VariousLayoutsDemo.java

java  VariousLayoutsDemo 
 
Figure 4: Bat file used to compile and run VariousLayoutsDemo example

How to create the various files in the VariousLayoutsDemo example code

To run this example,

  1. Cut and paste the code in Figure 3 and place it in a file called VariousLayoutsDemo.java.
  2. Cut and paste the code in Figure 4 and place it in a file called VariousLayoutsDemo.bat.
  3. Double click on the VariousLayoutsDemo.bat file and you will see the following.

  4. If you want to see the classes and methods created by javadoc, cut and paste the following code into a javadoc.bat file:
     
    javadoc   VariousLayoutsDemo.java
     
You will note that the various layouts are changed depending the selected choice.








[HOME] [Consulting] [Design] [Maintenance] [Project] [Testing] [Training] [Turnkey] [Java] [C++] [SQL] [HTML] [JavaScript ]

© 2002 - 2009 All Rights Reserved Total Application Works