Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

Java Beans Tutorial, Pt. 4: Events and ActionListeners for ChoiceApplet

 
Training Index


[Tutorial Contents]

In this section you'll see a mixture of JDK 1.0 and JDK 1.1 event handling. It's highly discouraged that you mix the event models in actual programs. But this does show that, to some extent, the models will work together. Start by adding a TextField to ChoiceApplet02

  TextField   theTextField = new TextField(20);
Now add the the TextField to the applet and add an ActionListener:
  add(theTextField);
  theTextField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      System.out.println(
        "ENTER----->ActionListener");
      String mName = e.getActionCommand();
      System.out.println("mName: " + mName);
      System.out.println(
        "EXIT------>ActionListener");
    }
  });


The call to addActionListener uses an inner class definition, which is created inside single argument given to addActionListener. Inner classes provide a powerful mechanism for simplifying code and consolidating code for event registration and event handling in a single location. Without the inner class mechanism, a separate ActionListener sublcass would have to be written to handle the actionPerformed events generated by the TextField. These events are generated whenever the return key is pressed, with input focus on the TextField.

Currently the actionPerformed event handler only prints out the name of the event that was fired. You'll get a chance to add more useful information and actions in the next section.

In order to use ActionListeners in your code you need to add the following import statement at the top of the file:

import java.awt.event.*;

You can use TestChoiceApplet02.html to test the applet.

Program Source Code

A makefile for this lesson automates source code compilation.

You may want to look at the final source file for ChoiceApplet02.java to verify the changes.