Layout Managers

The following program illustrates the use of Layout Managers. To run the program uncomment the section on a particular Layout Manager and comment out those that you do not want. Compile the program and run it.

import java.awt.*;

public class LayoutManagerDemo 
{
  public static void main ( String [] args ) 
  {
    //  Create the frame
    Frame frame = new Frame ( "Layout Manager Demo" );
    
    /*  Demonstrate Flow Layout  
    CheckboxGroup size = new CheckboxGroup ();
	
    Checkbox cb1 = new Checkbox ("Large", size, false);
    Checkbox cb2 = new Checkbox ("Medium", size, false);
    Checkbox cb3 = new Checkbox ("Small", size, false);
		
    frame.setLayout ( new FlowLayout () );
    frame.add (cb1); frame.add (cb2); frame.add (cb3);		
    frame.pack ();
    frame.setVisible ( true ); 
    */
		
    /*  Demonstrate Grid Layout  
    Label xLabel = new Label ("X Coordinate");
    Label yLabel = new Label ("Y Coordinate");
    TextField xInput = new TextField (5);
    TextField yInput = new TextField (5);
		
    frame.setLayout (new GridLayout(2,2,20,20));
    frame.add(xLabel);  frame.add(xInput);
    frame.add(yLabel);  frame.add(yInput);
    frame.pack ();
    frame.setVisible ( true );
    */
		
    /*  Demonstrate Border Layout 
    TextField header = new TextField ("Title");
    header.setEditable (false);
		
    TextField footer = new TextField ("Footnote");
    footer.setEditable (false);
		
    Scrollbar sb1 = new Scrollbar (Scrollbar.VERTICAL, 0, 1, 0, 255);
    Scrollbar sb2 = new Scrollbar (Scrollbar.VERTICAL, 0, 1, 0, 255);
		
    Canvas drawRegion = new Canvas();
    drawRegion.setSize (150,150);
    drawRegion.setBackground (Color.red);
		
    frame.setLayout (new BorderLayout());
    frame.add (header, BorderLayout.NORTH);
    frame.add (footer, BorderLayout.SOUTH);
    frame.add (sb1, BorderLayout.WEST);
    frame.add (sb2, BorderLayout.EAST);
    frame.add (drawRegion, BorderLayout.CENTER);
    frame.pack ();
    frame.setVisible ( true );
    */
		
    /*  Demonstrate Grid Bag Layout  */ 
    String colors[] = {"Violet", "Indigo", "Blue", "Green", 
		       "Yellow", "Orange", "Red"};
    List colorList = new List (colors.length-2, false);
    for (int i = 0; i < colors.length; i++)
	colorList.add (colors[i]);
			
    Label shape = new Label ("Shape");
    shape.setFont (new Font("Times", Font.BOLD, 14));
		
    Choice shapeChoice = new Choice();
    shapeChoice.add("Triangle");  shapeChoice.add("Square");
    shapeChoice.add("Rectangle");  shapeChoice.add("Polygon");
		
    Checkbox cbFill = new Checkbox ("Fill", false);
    cbFill.setFont (new Font("Times", Font.BOLD, 14));
		
    frame.setLayout (new GridBagLayout());
		
    GridBagConstraints gbc = new GridBagConstraints();
		
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.weightx = 1;  gbc.weighty = 0;

    addUsingGBL (frame, colorList, gbc, 0, 0, 1, 3);
    addUsingGBL (frame, shape, gbc, 1, 0, 1, 2);
    addUsingGBL (frame, shapeChoice, gbc, 2, 0, 1, 2);
    addUsingGBL (frame, cbFill, gbc, 1, 2, 2, 1);

    frame.pack ();
    frame.setVisible ( true );
    }
	
    public static void addUsingGBL (Frame frame, Component component, 
				    GridBagConstraints gbc, int x, 
				    int y, int w, int h) 
    {
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = w;
      gbc.gridheight = h;
      frame.add (component, gbc);
    }

}

Event Handling

GUI applications are event-driven. Clicking a button, closing a window, or hitting a key results in an appropriate event being sent to the application. Event handling in Java is based on the event delegation model. Its principal elements are: Handling events in a GUI application using the event delegation model can be divided into the following two tasks when building an application: The superclass of all events is java.util.EventObject. The class java.util.EventObject has a subclass java.awt.AWTEvent, which is the superclass of all AWT-related event classes. These AWT event classes all reside in the java.awt.event package and represent categories of events. It is useful to divide the subclasses of the AWTEvent class further into two groups - Semantic Events and Low-level Events.

Semantic Events

The following describes each of the semantic event classes:

ActionEvent - This event is generated by an action performed on a GUI component.

AdjustmentEvent - This event is generated when adjustments are made to an adjustable component like a scrollbar.

ItemEvent - This event is generated when an item is selected or de-selected in a component.

TextEvent - This event is generated whenever the content of a text component is changed.

Low-level Events

The following describes each of the low-level events:

AWT events are represented by the subclasses of the java.awt.AWTEvent class. The source of an event can be identified by calling the getSource() method, and the event's type value determined by calling the getID() method. In the event delegation model, an event source informs event listeners about events when these occur.

How is the association between the source and the listener established? Each event source defines methods for registering (addXListener()) and removing (removeXListener()) listeners which implement a particular listener interface (Xlistener). Each Xlistener interface defines methods that accept specific event type as argument.

Semantic Event Handling

Event Type Event Source Event Listener
ActionEvent Button ActionListener
List
MenuItem
TextField
AdjustmentEvent Scrollbar AdjustmentListener
ItemEvent Choice ItemListener
Checkbox
CheckboxMenuItem
List
TextEvent TextArea TextListener
TextField


Semantic Event Listener Interfaces and Their Methods

Event Listener Interface Event Listener Methods
ActionListener actionPerformed ( ActionEvent evt )
AdjustmentListener adjustmentValueChanged ( AdjustmentEvent evt )
ItemListener itemStateChanged ( ItemEvent evt )
TextListener textValueChanged ( TextEvent evt )


Low Level Event Handling

Event Type Event Source Event Listener
ComponentEvent Component ComponentListener
ContainerEvent Container ContainerListener
FocusEvent Component FocusListener
KeyEvent Component KeyListener
MouseEvent Component MouseListener
MouseMotionListener
WindowEvent Window WindowListener


Low Level Event Listener Interfaces and Their Methods

Event Listener Interface Event Listener Methods
ComponentListener componentHidden ( ComponentEvent evt )
componentMoved ( ComponentEvent evt )
componentResized ( ComponentEvent evt )
componentShown ( ComponentEvent evt )
ContainerListener componentAdded ( ContainerEvent evt )
componentRemoved ( ContainerEvent evt )
FocusListener focusGained ( FocusEvent evt )
focusLost ( FocusEvent evt )
KeyListener keyPressed ( KeyEvent evt )
keyReleased ( KeyEvent evt )
keyTyped ( KeyEvent evt )
MouseListener mouseClicked ( MouseEvent evt )
mouseEntered ( MouseEvent evt )
mouseExited ( MouseEvent evt )
mousePressed ( MouseEvent evt )
mouseReleased ( MouseEvent evt )
MouseMotionListener mouseDragged ( MouseEvent evt )
mouseMoved ( MouseEvent evt )
WindowListener windowActivated ( WindowEvent evt )
windowClosed ( WindowEvent evt )
windowClosing ( WindowEvent evt )
windowDeactivated ( WindowEvent evt )
windowDeiconified ( WindowEvent evt )
windowIconified ( WindowEvent evt )
windowOpened ( WindowEvent evt )


Any listener of a Button object that wants to be informed of an Action Event must implement the corresponding ActionListener interface. This interface specifies only one method: actionPerformed (ActionEvent evt). This method will be invoked on the listener, with the information about the event supplied in the ActionEvent argument, when the button is clicked. The listener can take appropriate action to handle the event in its implementation of the actionPerformed ( ActionEvent evt ) method.

The first program is fairly simple. It shows how to handle events. There is button control that can toggled ON or OFF.

import java.awt.*;
import java.awt.event.*;

public class SimpleFrame extends Frame
{
  public Button toggle;
  public ButtonListener buttonListener;

  public SimpleFrame ()
  {
    // Create a window
    super ( "Simple Frame" );

    // Create one button
    toggle = new Button ( "ON" );

    // Set a flow layout manager
    setLayout ( new FlowLayout ( FlowLayout.CENTER ) );

    // Add the button
    add ( toggle );

    // Create and add the listener to the button
    buttonListener = new ButtonListener ( this );
    toggle.addActionListener ( buttonListener );

    // Pack the window and make it visible
    pack();
    setVisible ( true );
  }

  public static void main ( String [] args )
  {
    new SimpleFrame ();
  }
}

class ButtonListener implements ActionListener
{
  private SimpleFrame theFrame;

  public ButtonListener ( SimpleFrame aFrame )
  {
    theFrame = aFrame;
  }

  public void actionPerformed ( ActionEvent evt )
  {
    if ( evt.getSource() == theFrame.toggle )
    {
      String str = theFrame.toggle.getLabel();
      if ( str.equals ( "ON" ) )
        theFrame.toggle.setLabel ( "OFF" );
      else
	theFrame.toggle.setLabel ( "ON" );
    }
  }
}


The second program shows how to use a graphical user interface to input and output data.

import java.awt.*;
import java.awt.event.*;

public class AddTwo extends Frame
{
  public Button sButton;
  public TextField xField;
  public TextField yField;
  public TextField sField;
  public ButtonListener buttonListener;
  
  public AddTwo ()
  {
     // Create a window
     super ( "Add Two Numbers" );
     
     // Create the controls
     Label xLabel = new Label ( "Enter x: " );
     Label yLabel = new Label ( "Enter y: " );
     sButton = new Button ( " Sum " );
     
     xField = new TextField ( 20 );
     xField.setEditable ( true );
     yField = new TextField ( 20 );
     yField.setEditable ( true );     
     sField = new TextField ( 20 );
     sField.setEditable ( false );
     
     // Set the Grid Layout Manager
     setLayout ( new GridLayout ( 3, 2 ) );
     
     // Add the controls
     add ( xLabel );   add ( xField );
     add ( yLabel );   add ( yField );
     add ( sButton );  add ( sField );
     
     // Create and add the listener to the button
     buttonListener = new ButtonListener ( this );
     sButton.addActionListener ( buttonListener );
     
     // Pack the window and make it visible
     pack();
     setVisible ( true );
  }
  
  public static void main ( String [] args )
  {
    new AddTwo ();  
  }
}

class ButtonListener implements ActionListener
{
  private AddTwo aFrame;
  
  public ButtonListener ( AddTwo someFrame )
  {
    aFrame = someFrame;
  }
  public void actionPerformed ( ActionEvent evt )
  {
      if ( evt.getSource() == aFrame.sButton )
      {
        String xStr = aFrame.xField.getText();
        double x = Double.parseDouble ( xStr );
        
        String yStr = aFrame.yField.getText();
        double y = Double.parseDouble ( yStr );
        
        aFrame.sField.setText ( String.valueOf ( x + y ) );
      }
  }
}


In this example the user closes the window by clicking its close box and the application terminates. Clicking the close box results in the event source (which is a Window or a subclass of Window) calling the windowClosing ( WindowEvent evt ) method of the WindowListener interface.

import java.awt.*;
import java.awt.event.*;

public class SimpleWindow extends Frame
{
  public Button qButton;
  public QuitHandler quitHandler;

  public SimpleWindow ()
  {
    // Create a window
    super ( "Simple Window" );

    // Create one button
    qButton = new Button ( "Quit" );

    // Set a flow layout manager
    setLayout ( new FlowLayout ( FlowLayout.CENTER ) );

    // Add the button
    add ( qButton );

    // Create and add the listener to the button
    quitHandler = new QuitHandler ( this );
    qButton.addActionListener ( quitHandler );
    
    // Add the listener to the window
    addWindowListener ( quitHandler );

    // Pack the window and make it visible
    pack();
    setVisible ( true );
  }

  public static void main ( String [] args )
  {
    new SimpleWindow ();
  }
}

class QuitHandler implements ActionListener, WindowListener
{
  private SimpleWindow theWindow;

  public QuitHandler ( SimpleWindow aWindow )
  {
    theWindow = aWindow;
  }

  // Terminate the application
  private void terminate ()
  {
    System.out.println ( "Quitting the application" );
    theWindow.dispose();
    System.exit (0);
  }

  // Invoked when the user clicks the quit button
  public void actionPerformed ( ActionEvent evt )
  {
    if ( evt.getSource() == theWindow.qButton )
      terminate ();
  }
  
  // Invoked when the user clicks the close-box
  public void windowClosing ( WindowEvent evt )
  {
    terminate ();
  }
  
  // Unused methods of the WindowListener interface
  public void windowOpened ( WindowEvent evt ) {}
  public void windowIconified ( WindowEvent evt ) {}
  public void windowDeiconified ( WindowEvent evt ) {}
  public void windowDeactivated ( WindowEvent evt ) {}
  public void windowClosed ( WindowEvent evt ) {}
  public void windowActivated ( WindowEvent evt ) {}
}