Programming Languages‎ > ‎Java‎ > ‎

09. Java GUI (Part 2)

Layout Managers

  • Layout managers define the spatial relationships between components in a container. 
  • Some IDEs (like NetBeans) have the drag-and-drop capability for laying out GUI components. 
  • If the IDE you use doesn't have the drag-and-drop capability or if it makes more sense to programmatically set the layout, you should use one or more of the layout classes.

Layout classes are:

  • class java.awt.BorderLayout - up to five (5) components can be placed in locations BorderLayout.north, BorderLayout.south, BorderLayout.west, BorderLayout.east and

  • class java.awt.CardLayout - handles components are stack of cards with only the top being visible in the container

  • class java.awt.FlowLayout - lays out the components in rows growing from left to right, and rows from top to bottom (defaultfor the Panel & Applet classes)

  • class java.awt.GridBagLayout - Customizable and flexible layout manager that lays out components in a rectangular grid

  • class java.awt.GridLayout - lays out components in a specified rectangular grid from left to right in each row, filling rows top to bottom

NOTE: You may put only ONE component in each part of a layout (other than FlowLayout). Therefore, if you want to put more than one, use a JPanel (or Panel if an AWT program) which would be considered one component.

Examples of setting the layouts:

    • setLayout(new FlowLayout()); (inside JFrame subclass constructor)
    • JPanel mainPanel = new JPanel(new BorderLayout());
    • JPanel panel= new JPanel();  panel.setLayout(new GridLayout(5, 30); // sets 3 rows, 5 columns

Following example GUI program which uses BorderLayout and has JCheckBoxes in the WEST, corresponding JTextFields in the EAST, and JButtons in the SOUTH. In the WEST and EAST, there are JPanels in which each have a GridLayout. In the SOUTH, there's another JPanel with FlowLayout.

Output of program given in the above link:

Layout Example Program

  • Example program which uses BorderLayout and has Checkboxes with corresponding TextFields that are displayed when a button is pressed and its Checkbox is selected or when its Checkbox changes to selected.
  • Note there are JPanels in the WEST, EAST and SOUTH.

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

public class GUIExample extends JFrame                    
            implements ActionListener, ItemListener{      
      private JCheckBox[] cbs; 
      private String [] boxNames;
      private int arrSize;
      private JTextField[] tfs;
      private JButton displayBtn, clearBtn; 
      public GUIExample(String [] names){
            arrSize = names.length;
            boxNames = names;
            setLayout(new BorderLayout());// set layout for JFrame
            // Create panel with Checkboxes
            JPanel p1= new JPanel(
                  new GridLayout(arrSize, 1, 5, 5));
            cbs = new JCheckBox[arrSize];
            for( int i=0 ; i<arrSize ; ++i ){
                  cbs[i] = new JCheckBox(boxNames[i]);
                  cbs[i].addItemListener(this );
            } // end for
            // Create panel with TextFields
            JPanel p2 = new JPanel(
                  new GridLayout(arrSize, 1, 5, 5));              
            tfs = new JTextField[arrSize];
            for( int i=0; i<arrSize ; ++i ){
                  tfs[i] = new JTextField(18);
            } // end for
            // Create panel with a buttons
            JPanel p3 = new JPanel();
            displayBtn = new JButton("Display Selected");
            clearBtn = new JButton("Clear Text Fields");

            add(p1, BorderLayout.WEST); // checkboxes in WEST
            add(p2, BorderLayout.EAST); // textfields in EAST
            add(p3, BorderLayout.SOUTH); // buttons in SOUTH
      } // end constructor
      public void actionPerformed( ActionEvent e ){
            Object obj=e.getSource();
            String s;
            if( obj  == displayBtn ){ // Display Selected clicked
                  for( int i=0 ; i<arrSize ; ++i ){
                        if( cbs[i].isSelected() && //check box selected?
                             !(s=tfs[i].getText()).equals("") )//has text?
                             System.out.println(s);// JUST FOR DEMO
                  } // end for
            } // end if
            else if( obj == clearBtn ){// Clear Textfields clicked
                        for( int i=0 ; i < arrSize; ++i )
            } // end else
      } // end actionPerformed

      public void itemStateChanged( ItemEvent e ){
            JCheckBox cb= (JCheckBox) e.getSource();
            String s;
            //display ONLY if a check box was selected
            if( e.getStateChange() == ItemEvent.SELECTED ){
                  for( int i=0 ; i<arrSize ; ++i ){
                        if( cbs[i]== cb ){ // found Checkbox
                             if(!(s=tfs[i].getText()).equals("") )
                                      System.out.println(s); // JUST FOR DEMO
                             break ;
                         } // end if cbs 
                  } // end for
            } // end if
      } // end ItemStateChanged()
} // end class GUIExample

In a separate file:

public class TryGUIExample {
     public static void main( String[] args ){
          String [] strs=
              {"Name", "Company", "Email Address", "Phone"};
          GUIExample gui = new GUIExample(strs);
     } // end main

} // end class TryGUIExample

Java Applets

To create an applet, your class must subclass (extends) JApplet (in Swing) or Applet (in AWT). Every applet should override the following methods:

  • init - called by the browser/appletviewer'smain method when the applet is loaded.  This method is usually used to initialize the applet's variables.
  • any of the Interfaces needed to "listen" to GUI components in the applet (for example,actionPerformed, itemStateChanged)

In the applet:

  • override paint which will be called automatically by the browser or appletviewer during an applet's execution.  This methods is also automatically called when the applet window is resized or the browser's print command is executed (also called whenrepaint() is called).  You should never directly call paint.  The browser/appletviewer passes a Graphics object that refers to the applet's window on which you could "draw".
  • call add(...) to put components in the applet (recall that an applet is a subclass of Panel)

To execute an applet in your IDE, from the "Run" menu (or right-clicking the applet file), choose "Java Applet" run configuration (NOT the same as executing a Java application program).  This is running the applet in AppletViewer.

To run an applet in a browser, be sure the applet is loaded in the HTML file using the applet code.below. Recall that most IDEs will automatically create this when the applet project is created. If you don't use an IDE, write a HTML file, which should include:

<applet code="filename.class" 
     width=num-pixels height=num-pixels>

Note that the Applet code that is loaded and interpreted in a web page is not the Java source code, but Java bytecode, which is the output from the Java compiler (stored in a .class file).

Example of an Applet Program

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

public class TryButtonsApplet extends JApplet 
                    implements ActionListener {

JButton button1, button2;
JLabel outputLabel;

public void init() {

setLayout(new FlowLayout());// UPDATED!

button1 = new JButton("First Button");
button1.addActionListener( this );
button2 = new JButton("Second Button");
button2.addActionListener( this );
outputLabel = new JLabel();


} // end init

public void actionPerformed(ActionEvent e){

Object source = e.getSource();
if( source == (Object) button1 )
              outputLabel.setText("You chose the First Button");
else if( source == (Object) button2 )
                 outputLabel.setText("You chose the Second Button");

} // end actionPerformed

} // end class TryButtonsApplet