INTRODUCTION TO GRAPHICAL USER INTERFACES (GUIs)

Note: This WWW page was started in January 2000 before Java Swing. However, I have converted the examples so that they are now extensions of the JFrame class found in the javax.swing package (the original examples extended the Frame class found in the java.awt package.

CONTENTS

1. Introduction
2. First example (GUI with "push button"), using Swing
3. Event handling
4. Closing a window
5. Insets


1. INTRODUCTION

A Graphical User Interface (GUI) is an interface between a user and a computer that makes use of devices such as windows, menus and buttons to facilitate input. In Java a GUI comprises a set of components (e.g. buttons, menus, Etc.) which are placed in a container (e.g. or a window or frame). Components cannot be displayed outside of a container.

To create a GUI the classes in the java.awt and javax.swing packages that comes with the Java API are typically used.

AWT CLASS DIAGRAM

Figure 1: Partial class hierarchy of contents of java.awt package

From Figure 1 we can see that the class Component is the parent class of different types of component such as buttons as well as containers of different forms such as Wodows, Frames and JFrames. Four methods are given for the Component class in Figure 1 (there are more):

  1. setBackground(Color c) Sets then back ground colour of the component to a colour found in the class Color (e.g. yellow). There are 13 colours to choose from: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white and yellow.
  2. SetForeground(Color c) Sets the foreground color in a similar way that the setBackground method sets the backgound color.
  3. setSize(int w, int h) Resizes a component to the given width and height.
  4. setVisible(boolean b) Shows or hides this component depending on the value of parameter b.

The class Container (in Figure 1) gives two methods.

  1. add(Component comp) Adds the specified component to a container (e.g. places a "button" into a "frame".
  2. setLayout(LayoutManager mgr) Sets the layout of components within a container according to its argument which must be an instance of a sub-class that implement the interface LayoutManager (for example FlowLayout which arranges components in a left to right ordering.

Remember that the components cannot be displayed separately on the screen, but must be placed in a container. Components can be arranged in a container in a number of different ways according to something called the layout manager. For the time being we will be using the FlowLayout layout manager.

Note:


1.1. The JFrame class and Content Panes

The Frame class has a sub-class JFrame contained in the javax.swing package. This is a container like any other container in which components such as buttons and menues can be placed. The on-screen display area for a instance of the class JFrame, or its sub-classes, has a content pane. A content pane is an instance of the class Container to which the desired GUI components can be attached.

Before we can do anything with a GUI we must obtain a reference to the containers content pane. This is done (in the case of a JFrame) using the getContentPane method which returns a reference a JFrames's content pane object.



2. FIRST EXAMPLE (GUI WITH "PUSH BUTTON")

We create a GUI by first creating a container. We do this by defining a class that extends the class Container or some sub-class of this class, for example the class JFrame. There are essentially four steps to creating a simple GUI:

  1. Define a class that extends an existing style of container (we will be using JFrames) and obtain a reference to the container's content pane. Use this reference to decalre the nature of the layout manager to be used.
  2. Define the nature of the GUI (e.g. background and foreground colours) by including calls to the appropriate component class methods (e.g. setBackground, etc.) in the constructor for the GUI class.
  3. Define the contents of the GUI by creating instance of the components we wish to include (using the constructors found in the classes describing the desired components) and adding them to the container using the add method found in the Container class.
  4. Create an instances of the GUI class and assign values for instance attributes such as size and visibility (using the setSize and setVisible methods found in the Component class).

Some code to produce a simple example GUI (based on an example presented in Holmes, 1998) is given in Table 1 (the result is given in Figure 2). Note:

// GUI Example 1 
// Frans Coenen
// Wednesday 29 March 2000
// Revised Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

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

public class Gui1 extends JFrame {

    /* Constructor */
    
    public Gui1(String text) {
        super(text);
	
        Container container = getContentPane();
	container.setLayout(new FlowLayout());
	
	container.setBackground(Color.yellow);
        
        JButton pushButton = new JButton("press me");
        container.add(pushButton);
        }
    }

/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */   
    
class GuiEx1App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        Gui1 screen = new Gui1("GUI Example 1");
	screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        screen.setSize(500,100);
        screen.setVisible(true);
        }
    }

Table 1:Code to create a simple example GUI

Example GUI 1

Figure 2: Result of exacuting code presented in Table 1.



3. HANDLING EVENTS

In the example presented above nothing happens when we click on the button. This is because we have not included anything in the code presented in Table 1, to (a) detect a mouse click or (b) do anything about it. Occurences such as mouse clicks are called events. To detect such an event we need to include an appropriate event listener. Different components have different listeners associated with them:

There are also other sorts of listener, for example mouse listeners. The different kinds of listener are described by a set of interfaces which implement the EventListener interface.

Thus in the case of our button component we need to include an action listener. We do this with a call to the addActionListener method found in the Button class. When an action event is detected by the action listener the actionPerformed() method contained in the ActionListener interface is automatically invoked. However, because ActionListener is an interface, we must implement this method in our Gui class. Note (from Figure 1) that this method is called with a single argument which must be an instance of the class ActionListener. Such an instance is created automatically on detection of an action event.

Thus to summarise, to react to a button press we must do the following:

  1. Add an action listener, e.g. the addActionListener method contained in the Button class.
  2. Implement the actionPerformed method whose signature is contained in the ActionListener interface.

Some sample code which sounds a "beep" (unicode \u0007) when the button is pressed is presented in Table 2.

// GUI Example 2 
// Frans Coenen
// Wednesday 29 March 2000
// Revised Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

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

public class Gui2 extends JFrame implements ActionListener {

    /* Constructor */
    
    public Gui2(String text) {
        super(text);
	
        Container container = getContentPane();
	container.setLayout(new FlowLayout());
	
	container.setBackground(Color.yellow);
        
        JButton pushButton = new JButton("press me");
        container.add(pushButton);
	
	// Register event handlers
	
	pushButton.addActionListener(this);
        }

    /* Action Performed */
                   
    public void actionPerformed(ActionEvent event) {
        final char BELL = '\u0007';
                       
        if (event.getActionCommand().equals("press me")) System.out.print(BELL);
        }
    }

/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */   
    
class GuiEx2App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        Gui2 screen = new Gui2("GUI Example 1");
	screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        screen.setSize(500,100);
        screen.setVisible(true);
        }
    }

Table 2:Event handling code

Note that the getActionCommand method returns the command string associated with the indicated action. In the case of a button it is its label (in the case of a text field it is the entered text, but more on this later). An alternative encoding for the above actionPerformed method might be:

public void actionPerformed(ActionEvent event) {
        final char BELL = '\u0007';
	
	Object source = event.getActionCommand);
	
	if source.equals("press me")) System.out.print(BELL);
	}

This is useful if we need to check the command string more than once.



4. CLOSING A WINDOW

The usual way of closing a window is by selecting a "close" option from a menu or by clicking on the X icon (top right hand corner of the title bar). In the above examples we used the default close operation JFrame.EXIT_ON_CLOSE.

When not using Swing we must write our own window listener. An Example is given in Table 3 using a Frame container.

// GUI Example 4 
// Frans Coenen
// Wednesday 29 March 2000
// Dept. of Comp. Sci., University of Liverpool

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

public class Gui4 extends Frame implements WindowListener, ActionListener {

    /* Constructor */
    
    public Gui4(String text) {
        super(text);
	
        setLayout(new FlowLayout());
	
	setBackground(Color.yellow);
        
        Button pushButton = new Button("press me");
        add(pushButton);
	
	// Register event handlers
	
	pushButton.addActionListener(this);
        addWindowListener(this);
	}

    // --------------------------------- METHODS ------------------------------
      
    /* Action Performed */
    
    public void actionPerformed(ActionEvent event) {
        final char BELL = '\u0007';
        
        if (event.getActionCommand().equals("press me")) System.out.print(BELL);
        }
            
    /* Window Closed */
    
    public void windowClosed(WindowEvent event) {
        }

    /* Window Deiconified */
    
    public void windowDeiconified(WindowEvent event) {
        }

    /* Window  Iconified */
    
    public void windowIconified(WindowEvent event) {
        }

    /* Window Activated */
    
    public void windowActivated(WindowEvent event) {
        }

    /* Window Deactivated */
    
    public void windowDeactivated(WindowEvent event) {
        }

    /* Window Opened */
    
    public void windowOpened(WindowEvent event) {
        }

    /* Window Closing */
    
    public void windowClosing(WindowEvent event) {
        System.exit(0);
        } 
    }

/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */     

class GuiEx4App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        Gui4 screen = new Gui4("GUI Example 1"); 
        
        screen.setSize(500,100);
        screen.setVisible(true);
        }
    }

Table 4:Closing a Frame

Alternatively a window can be closed from another window using the method dispose(), linked to the name of the window to be closed, and called from another window.



5. INSETS

An instance of the class Insets is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title. The Insets class has four fields: bottom, left, right and top representing the inset, expressed as a number of pixels (an int) for the indicated corner. To find the values or these four fields the Container class includes a method getInsets which obtains the insets of the this container, which in turn indicates the size of the container's border. Some example code which uses this method is given in Table 4.

// GUI Example 4
// Frans Coenen
// Wednesday 29 March 2000
// Revised Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

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

public class Gui4 extends JFrame {

    /* Constructor */
    
    public Gui4(String text) {
        super(text);
	
        Container container = getContentPane();
	container.setLayout(new FlowLayout());
	
	container.setBackground(Color.yellow);
        }
    }

/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */    

class GuiEx4App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        Gui4 screen = new Gui4("GUI Example 1");
	screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        screen.setSize(500,100);
        screen.setVisible(true);
	
        // Get insets
	
	Insets insets = screen.getInsets();
	System.out.println("insets.left = " + insets.left);
	System.out.println("insets.right = " + insets.right);
	System.out.println("insets.top = " + insets.top);
	System.out.println("insets.bottom = " + insets.bottom);}
    }

Table 4:Insets

The resulting output is a GUI similar to that shown in Fihure 2 (but without the button) abd some screen output as follows:

insets.left = 5
insets.right = 6
insets.top = 25
insets.bottom = 5     

Thus banner at the top of the window has a height of 25 pixels, the vertcal borders a width of 5 and 6 pixels, and the bottom border a height of 5 pixels also.



REFERENCES

  1. Holmes, B. (1998). Programming with java. Jones and Bartlett, London, p362.



Created and maintained by Frans Coenen. Last updated 01 July 2003