Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Online Training

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
 
Training Index

Java Beans Tutorial, Part 4
Events and ActionListeners for ChoiceApplet

By Greg Voss, JavaSoft

[Tutorial Contents]

In this section you'll see a mixture of JDKTM 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.


[ This page was updated: 5-Nov-99 ]

Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-99 Sun Microsystems, Inc.
All Rights Reserved. Legal Terms. Privacy Policy.