Capturing an event

Bruce Eckel’s Thinking in Java Contents | Prev | Next

You’ll
notice that if you compile and run the applet above, nothing happens when you
press the buttons. This is where you must step in and write some code to
determine what will happen. The basis of event-driven
programming, which comprises a lot of what a GUI is about, is tying events to
code that responds to those events.

After
working your way this far through the book and grasping some of the
fundamentals of object-oriented programming, you might think that of course
there will be some sort of object-oriented approach to handling events. For
example, you might have to inherit each button and override some “button
pressed” method (this, it turns out, is too tedious and restrictive). You
might also think there’s some master “event” class that
contains a method for each event you want to respond to.

Before
objects, the typical approach to handling events was the “giant switch
statement.” Each event would have a unique integer value and inside the
master event handling method you’d write a
switch
on that value.

The
AWT in Java 1.0

doesn’t use any object-oriented approach. Neither does it use a giant
switch
statement that relies on the assignment of numbers to events. Instead, you must
create a cascaded set of
if
statements. What you’re trying to do with the
if
statements is detect the object that was the
target
of the event. That is, if you click on a button, then that particular button is
the target. Normally, that’s all you care about – if a button is
the target of an event, then it was most certainly a mouse click and you can
continue based on that assumption. However, events can contain other
information as well. For example, if you want to find out the pixel location
where a mouse click occurred so you can draw a line to that location, the
Event
object will contain the location. (You should also be aware that Java 1.0
components can be limited in the kinds of events they generate, while Java 1.1
and Swing/JFC components produce a full set of events.)

The
previous example can be extended to handle button clicks as follows:

//: Button2.java
// Capturing button presses
import java.awt.*;
import java.applet.*;
 
public class Button2 extends Applet {
  Button
    b1 = new Button("Button 1"),
    b2 = new Button("Button 2");
  public void init() {
    add(b1);
    add(b2);
  }
  public boolean action(Event evt, Object arg) {
    if(evt.target.equals(b1))
      getAppletContext().showStatus("Button 1");
    else if(evt.target.equals(b2))
      getAppletContext().showStatus("Button 2");
    // Let the base class handle it:
    else
      return super.action(evt, arg);
    return true; // We've handled it here
  }
} ///:~ 

For
this example, the simplest action is to print what button is pressed. Some
systems allow you to pop up a little window with a message in it, but applets
discourage this. However, you can put a message at the bottom of the
Web
browser window on its
status
line

by calling the
Applet
method
getAppletContext( )
to get access to the browser and then
showStatus( )
to put a string on the status line.
[56]
You can print out a complete description of an event the same way, with
getAppletContext().showStatus(evt
+ “” ).
(The
empty
String
forces the compiler to convert
evt
to a
String.)
Both of these reports are really useful only for testing and debugging since
the browser might overwrite your message.

//: Button3.java
// Matching events on button text
import java.awt.*;
import java.applet.*;
 
public class Button3 extends Applet {
  Button
    b1 = new Button("Button 1"),
    b2 = new Button("Button 2");
  public void init() {
    add(b1);
    add(b2);
  }
  public boolean action (Event evt, Object arg) {
    if(arg.equals("Button 1"))
      getAppletContext().showStatus("Button 1");
    else if(arg.equals("Button 2"))
      getAppletContext().showStatus("Button 2");
    // Let the base class handle it:
    else
      return super.action(evt, arg);
    return true; // We've handled it here
  }
} ///:~ 

It’s
difficult to know exactly what the
equals( )
method is doing here. The biggest problem with this approach is that most new
Java programmers who start with this technique spend at least one frustrating
session discovering that they’ve gotten the capitalization or spelling
wrong when comparing to the text on a button. (I had this experience.) Also, if
you change the text of the button, the code will no longer work (but you
won’t get any compile-time or run-time error messages). You should avoid
this approach if possible.


[56]
ShowStatus( )
is also a method of Applet, so you can call it directly, without calling
getAppletContext( ).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read