Java Programming   Java Programming
 |Sofia Home | Content Gallery |
Home
Syllabus
Schedule
Lessons
Assignments
Resources

Lesson 5.5 Java"action" Events

In Java, there are two ways to handle events. Java 1.1 which we've been using up until now, uses a subscription model. In Java 1.1, to perform an action when a Button is clicked, you:
  • import the Java 1.1 event package
  • write a method or class to handle the event
  • tell the Button to send events to your handler
Java 1.0, the original version of Java, uses a little different scheme, a kind of broadcast model. Under this plan:
  • events are broadcast to the Button's container
  • you write a method to handle the event
  • you "consume" the event or pass it on to your superclass
You have already had considerable experience dealing with ActionEvents, the Java 1.1 event mechanism. In this section, you'll learn to handle the earlier, Java 1.0 style, "action" events. In addition, you'll meet a few more inherited Component methods that you might find useful.

Java 1.0 Event Handling

With Java 1.0, the version of Java understood by the greatest number of Web browsers, every user action--such as moving the mouse or clicking on a button--generates an event which is sent to a method called, appropriately, handleEvent()

You can override the handleEvent() method in your own programs, but you don't have to because the built-in handleEvent() method automatically calls a set of "convenience" methods which are somewhat easier to use. The action() method is one of those convenience methods.

The action() Method

The action() method is called in response to a variety of different user actions. If you click on a button, the action() method is called. If you press ENTER while typing in a text field, the action() method is also called. As we'll see later in the course, there are other events that call the action() method as well, such as selecting an item from a menu or checking and unchecking a checkbox.

The Arguments

Unlike the Java 1.1 actionPerformed() method, where all the information is packaged into a single ActionEvent object, the Java 1.0 action() method is passed two arguments, an Event object--which we'll name ev in this discussion--and an Object reference--which we'll name obj.

You might expect that obj would refer to the object which generated the action event--the Button that was clicked, for instance. That's not the case. Instead the value of the obj argument differs according to the type of component that generates the event. For Button objects, obj contains a reference to the button's label--what's printed on its face. For TextField objects, obj contains a reference to the text contained inside the field.

The most useful of the arguments passed to the action() method is the target field, which is a public field inside the Event argument, ev. This field does contain a reference to the object which generated the action event. Thus, you can use the equality operator, and simple selection, to take different actions when the user clicks on different buttons.

Back to Top

An Example

Here's an example that you've already seen [and modified] under the Java 1.1 model, Example5a.java. Let's take the code and change it so that it runs under the Java 1.0 model. We'll call the program Example5o.java, [five-oh, not five-zero] to distinguish it from the original. 

The necessary changes are marked in the code. Those items that need to be deleted are shown in grey using a strike-through font. Those items that need to be added are shown in red.
Example5o.java - Java 1.0 Event Handling
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Example5ao extends Applet
     implements ActionListener
{
  Button green = new Button("Green");
  Button red   = new Button("Red");

  public void init()
  {
    add(red);
    add(green);
    red.addActionListener(this);
    green.addActionListener(this);
  }

  public void 
  actionPerformed(ActionEvent e)
  public boolean 
  action(Event ev, Object obj)
  {
    Object pressed = e.getSource()
                ev.target;

    if (pressed == red)
      setBackground(Color.red);
    else
      setBackground(Color.green);

    return true;
  }
}

Back to Top

Looking at Example5o

The first thing you're likely to notice is that using the Java 1.0 model requires less code. We were able to remove:
  • the java.awt.event package import statement
  • implements ActionListener from the header
  • both addActionListener() messages in init()
The second thing you'll notice is that the structure of the code isn't all that different. We had to change the method header from actionPerformed() to action(), and change the arguments, of course. But there are only two other differences in the body of the method.

First, we had to retrieve a reference to the object that generated the event by directly using the public field ev.target, rather than using a method call like e.getSource().
ev.target vs. e.getSource()
One of the things that Sun was roundly criticized for in Java 1.0 was the number of public fields like ev.target. In Java 1.1, they cleaned this up considerably, making most internal data members private and providing accessor and mutator methods when appropriate. You'll learn more about accessor and mutator methods in Lesson 9.

Returning a Value

The second difference is that we had to return a true/false value. This is potentially one of the most confusing aspects of the Java 1.0 event model. What does it mean to return true or false? It's not really very intuitive.

The Java 1.0 event handling methods (including action()) all return a boolean value. Normally, from an applet action() method, you'll return true, which means "Yes, I've handled this; nobody needs to do anything else." 

This is called consuming the event. If you return false, on the other hand, you are telling Java "No, I didn't completely handle this; please find someone else who will". This is called "propogating the event" up the "containment hierarchy". You'll rarely do this, unless you have series of classes, each containing components, and you wish to "funnel" all the event handling to a particular class.

All in all, as you can see, the Java 1.0 event model is less work to get started, but with many components, it becomes very confusing very quickly. The Java 1.1 event model requires more work to set up, but each event and its handlers are explicitly specified and cleanly separated from the others.

What is Deprecation?

When you compile Example5o.java, which you'll do as part of the wrap-up section, the compiler will display the following message:

C:\JavaOnline\unit5>javac Example5o.java
Note: Example5o.java uses a deprecated API. 
         Recompile with "-deprecation" for details.
1 warning

This is called a deprecation warning. Deprecation means that Sun has added a method to the API that works better than a method you are using. Deprecation warnings help you to avoid accidentally using an old-style method when you don't mean to, but they can be disconcerting if you are purposely trying to write a Java 1.0 applet that will run on the widest number of browsers.
Do Not Be Alarmed!
You will always get this warning whenever you use any Java 1.0 event methods because Sun wants you to use the Java 1.1 event model instead. You do not have to worry when you get this message; it is not an error.

Back to Top

Working with Components

There are several things you may want to do as you work with different AWT components. For instance, you may want to disable a "Save" button until the user has entered some valid data, and then reenable it later. A disabled component does not generate events.

Java 1.1 vs Java 1.0
In Java 1.1, Sun changed the name of the method used to enable and disable components, and deprecated the older methods. If you are creating applets that are going to run on the Web, you should still use the older methods because the newer methods will not run in a browser that only supports Java 1.0. (This includes the Netscape browsers prior to version 4.07 for Unix and the PC, and all Netscape versions prior to 4.61 for the Macintosh).

Assuming you have a Button object named myButton that you want to disable and enable, here's how you do it:
Enabling and Disabling Components
// Java 1.0 style
myButton.enable(false); // Disable
myButton.enable(true);  // Enable 
myButton.enable();      // Also enable 

// Java 1.1 style
myButton.setEnabled(false); // Disable myButton.setEnabled(true);  // Enable

Back to Top

Focus

Both Button object and TextField objects need to have the "keyboard focus" if you want to use them from the keyboard. 

You can give a component the keyboard focus by clicking on it, but frequently, you'd like to do it programmatically. To do so, you use the requestFocus() method. To set the keyboard focus to the TextField named addressTF, do this:

addressTF.requestFocus();

When you set the focus to a TextField, the text inside is not automatically selected, so what you type is simply added to what is already there. If you want to automatically select all of the text so that what you type replaces what was previously there, you can use the selectAll() method like this:

addressTF.requestFocus();
addressTF.selectAll();

Something to Talk About

Here's an easy project. Download Example5a.java. What changes do you need to make so that it works with Java 1.0? [Be sure you compile and test your changes.]

Please continue to the next section of this lesson.

 

Back to Top

 

Content Developed by Stephen Gilbert, Licensed under a Creative Commons License
Published by the Sofia Open Content Initiative
© 2004 Foothill-De Anza Community College District &The William and Flora Hewlett Foundation