Event Tutor Applet
# The following applet is designed to give you some feel for just what event driven programming is like and what the various events you’re likely to encounter are. Whenever an event occurs, the applet responds by printing the name of the event at the command line.
import java.applet.Applet;
import java.awt.*;
public class EventTutor extends Applet {
public void init() {
System.out.println(”init event”);
}
public void paint(Graphics g) {
System.out.println(”paint event”);
}
public void start() {
System.out.println(”start event”);
}
public void destroy() {
System.out.println(”destroy event”);
}
public void update(Graphics g) {
System.out.println(”update event”);
}
public boolean mouseUp(Event e, int x, int y) {
System.out.println(”mouseUp event”);
return false;
}
public boolean mouseDown(Event e, int x, int y) {
System.out.println(”mouseDown event”);
return false;
}
public boolean mouseDrag(Event e, int x, int y) {
System.out.println(”mouseDrag event”);
return false;
}
public boolean mouseMove(Event e, int x, int y) {
System.out.println(”mouseMove event”);
return false;
}
public boolean mouseEnter(Event e, int x, int y) {
System.out.println(”mouseEnter event”);
return false;
}
public boolean mouseExit(Event e, int x, int y) {
System.out.println(”mouseExit event”);
return false;
}
public void getFocus() {
System.out.println(”getFocus event”);
}
public void gotFocus() {
System.out.println(”gotFocus event”);
}
public void lostFocus() {
System.out.println(”lostFocus event”);
}
public boolean keyDown(Event e, int x) {
System.out.println(”keyDown event”);
return true;
}
}
Once you’ve compiled and loaded this applet play with it. Click the mouse in the applet window. Doubleclick the mouse. Click and drag. Type some text. Resize the browser window. Cover it and then uncover it. Keep your eye on the standard output (Java console in Netscape) while doing this.
Here are some questions to answer:
# Can you have a mouseDown event that is not followed by a mouseUp event?
# Can you have a mouseDown event that is not followed by a mouseDrag event?
# Can you have a mouseUp Event that is not preceded by a mouseDown event?
# What has to happen for a paint event to occur?
# What’s the most common event? Why?
# Are there any events you don’t see?
# How many times can you make the start event get called? the stop event?
# Of those events you can make occur, exactly how do you do it? How many different ways can you do it? There are a number of new things in this code but none of them are particularly difficult. The first one is the second import statement, import java.awt.*. This time we need more than one class from the awt package so rather than worrying about which one to import, we just get them all with the *. The compiler is smart enough to only link in those that it actually uses.
Finally there are a whole lot of new event methods. We’ll cover them in detail in the next section. For now see under what circumstances you can make each one happen.