Lesson 2: Buttons, Events, and Text Fields

Lesson 2: Buttons, Events, and Text Fields

Maryland Flag Stripe

Gregory C. Walsh, Department of Mechanical Engineering

Introduction
Parameters
Code Details
My Version of the Applet
Remarks
Maryland Flag Stripe

Introduction

In this lesson we add buttons, text fields, and other GUI objects to our applet. These classes are defined in the Abstract Windowing Toolkit. Other classes of generate scrollbars, menus, and graphics windows.

We will create standard ones, since we don't need anything special in them. When the user interacts with such an object, say, clicks on a Button, the Button object is informed by the java virtual machine. The Button will then do several things, for example, it may redraw itself so it looks clicked. The Button also generates an Event. If the applet has an interface which can accept these Events, and if the Button has been told to inform your applet, then the event is passed through the interface to your applet. This is plenty of functionality for the simple programs I intend to write, so I will use standard Buttons.

In this lesson, we have three new jobs to do:

The GUI objects are created and added to the window in the Applet's init function, which we will override. One can think of the interface as a selective door for messages like Events which we will attach to the exterior of our applet. The interface amounts to a promise to the Java virtual machine that functions handling these various messages will be present. We must write them even if they do not do anything.

Parameters

Notice that the html code used to run the applet the parameters of height and width associated with it. If you experimented with the html code that I supplied in Lesson 1, you noticed this determines the size of the applet window. These parameters serve the same purpose as command line arguments in C, which are accessed by the argc and argv arguments of main. In java, we use the applet method getParameter , as seen in the example below.

Description of Code

We will examine the code line by line. The following code needs to be saved in a file called Lesson2.java.

// file: Lesson2.java
// type: Java code
// note: Handling buttons and fields
// author: Gregory C. Walsh
// date: 3.9.1999

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.applet.Applet;

public class Lesson2 extends Applet implements ActionListener{
    TextField input;
    Label output;
    Button zap, go, stop, reload;
    Font f;
    int ammo;
    
    public void init () {
	// Initialize amount of Ammo.  This is 
	// a parameter which may be passed from the 
	// html code which calls the applet.
	// The default value is 6

	String buffer = getParameter("ammo");
	if(buffer == null) {
	    ammo = 6;
	}
	else {
	    ammo = (int) Integer.valueOf(buffer).intValue();

	}
	// Pick Font for GUI objects

	f = new Font("TimesRoman",Font.PLAIN,16);

	// First generate the GUI objects and set fonts on gui's....

	output = new Label( "Ammunition = " + ammo,Label.CENTER);
	output.setFont(f);

	input  = new TextField( 20 );
	input.setFont(f);

	zap = new Button( "Zap!");
	zap.setFont(f);

	go = new Button("Go");
	go.setFont(f);

	stop = new Button("Stop");
	stop.setFont(f);

	reload = new Button("Reload");
	reload.setFont(f);

	// Connect GUI components to actionlistener ....

	zap.addActionListener(this);
	go.addActionListener(this);
	stop.addActionListener(this);
	reload.addActionListener(this);

	// Now add the components to the Applet 

	add(output);
	add(zap);
	add(go);
	add(stop);
	add(reload);
	add(input);

	// Configure the initial button state

	go.setEnabled(true);
	stop.setEnabled(false);
    }

    // Actionlistener for the buttons .....
    
    public void actionPerformed(ActionEvent e) {

	String command = e.getActionCommand();

	if( (command == "Zap!") && (stop.isEnabled()) ) {
	    if(ammo>0) {
		ammo--;
		Toolkit.getDefaultToolkit().beep();     
		output.setText("Ammo: " + ammo);
		input.setText(input.getText() + " Zap!!");
		if(ammo == 0) output.setText("Empty!");
	    }
	    else 
		output.setText("Out of ammo!");
	}
	
	if(command == "Go") {
	    showStatus(" ... Zap ready to go!");
	    go.setEnabled(false);
	    output.setText("Ammo: " + ammo);
	    stop.setEnabled(true);
	}

	if(command == "Reload") {
	    showStatus(" ... Zap on safety!");
	    go.setEnabled(true);
	    stop.setEnabled(false);
	    output.setText("Ammo reloaded");
	    ammo = 6;
	    input.setText("");
	}

	if(command == "Stop") {
	    showStatus(" ... Zap on safety!");
	    go.setEnabled(true);
	    stop.setEnabled(false);
	    input.setText("");
	}
	return;
    }
}

The first few lines are similar to the previous applet, Lesson1. However, notice we add some new data members to the definition of the WW1 class. In particular, we are adding four members of class Button, a member of class Label, a member of class TextField, and a member of class Font, all from the AWT. As you might imagine, there are many types of pre-written classes, producing slide bars, graphics, drop down lists, and so on. We will be using Button and Label primarily.

The first function we overide is the init function. Inside, notice first we create instances of the Font, the Button objects, and so on. We then set the font in these objects by calling methods of the objects, and finally, we call the add function, which hooks the object in and displays it in the window. No mention is made of placement, this will be discussed next lesson. We no longer need to override the paint function, you will notice. The paint function of each of the objects will be called when appropriate.

We also provide the function actionPerformed, which is required as this is a ActionListener. The code which follow merely checks to see what button was pressed by checking the string of the command. As there is no preprocessor, sometimes people use Static strings for the contents of buttons so that there is no confusion between the command idenfication and the name of the button itself.

My version of the applet

Remarks

Points to note are as follows:

  1. This lesson introduced the concept of an interface. It also showed how to use a basic GUI component, the Button. The Button could generate and event and provided that your application has the proper interface and the Button knew to inform your app, the app would be called when the Button was pushed.

  2. There are a large number of GUI components. The Button is the most basic and with the text field might be the only one you will need for your project. Having sliders, places to draw, and so on, are also good ideas. Try experimenting around with the GUI objects Scrollbar, Checkbox, Choice, Label, List, Canvas. Other objects include the Panel, MenuItem, TextArea, and TextField. Of course, we have not yet told you how to arrange the position of these components, that is for the next lesson. I refer you to either Austin and Chancogne or Campione and Walrath for a more complete listing of GUI components and their various events and listeners.

  3. There are many kinds of events. We have seen the ActionEvents. There are also AdjustmentEvent, ComponentEvent, ContainerEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, and WindowEvent. Typical GUI components like Canvas, Label, Component, all generate component, focus, key, mouse, and mousemotion events.

    Other GUI components generate events which are specialized to their nature.

        AWT Component    Type of Event
        ---------------------------------
        Button:          ActionEvent
        Choice:          ItemEvent
        List:            ItemEvent
        Checkbox:        ItemEvent
        Scrollbar:       AdjustmentEvent
        TextField:       ActionEvent
        ---------------------------------
    

    These events need listeners. The following listeners are useful for your Java project; consider this a set of starting points. Look up the full documentation on line at Sun or in Austin and Chancogne.

        Listener               Event Method
        ---------------------------------------------------------------
        ActionListener:        actionPerformed(ActionEvent);
        AdjustementListener:   adjustmentValueChanged(AdjustmentEvent);
        FocusListener:         focusGained(FocusEvent);
                               focusLost(FocusEvent);
        ItemListener:          itemStateChanged(ItemEvent);
        KeyListener:           keyPressed(KeyEvent);
                               keyReleased(KeyEvent);
                               keyTyped(keyEvent);
        MouseListener:         mouseClicked(MouseEvent); ...
        MouseMotionListener:   mouseDragged(MouseEvent);
                               mouseMoved(MouseEvent);
        TextListener:          textValueChanged(TextEvent);
        ---------------------------------------------------------------
    


Originally developed in 1999 by Greg Walsh
Modified in April 2001 by Mark Austin
Copyright © 1999-2001, Departments of Civil and Mechanical Engineering, University of Maryland