Counter: An Event-Driven Programming Example
The following example uses the "mouseUp," "mouseMove," and "Paint" methods to draw three things to the screen - The number of times you have clicked the applet and the x and y coordinates of the mouse pointer inside the applet. Here is the code and the applet:
import java.applet.Applet;
import java.awt.*;
public class Counter extends Applet {
int Clicks = 0;
int currentX;
int currentY;
public void paint(Graphics g) {
g.drawString(new Integer(Clicks).toString(), 5, 15);
g.drawString(new Integer(currentX).toString(), 30, 15);
g.drawString(new Integer(currentY).toString(), 55, 15);
}
public boolean mouseUp(Event evt, int x, int y) {
Clicks++;
repaint();
return true;
}
public boolean mouseMove(Event evt, int x, int y) {
currentX = x;
currentY = y;
repaint();
return true;
}
}
Go ahead, click it. You should notice a few things. The "mouseMove" and "mouseClick" methods are only called if the pointer is inside the applet. The code is not complicated. First, the variables "Clicks," "CurrentX," and "CurrentY" are not inside any of the methods so they are global variables. Whenever you click on the applet, it calls "MouseUp" method which adds one to the variable "Clicks," and whenever you move the pointer, it calls the "mouseMove" method which sets the variables "CurrentX" and "CurrentY" to the position of the cursor. Both of these methods call the "Repaint" method at the end. To be very specific, the "Repaint" calls the "update" method. The "update" method paints the background gray, and then calls the "paint" method. This allows the applet to update the information on the screen. The paint method writes the three global variables to the screen with the Graphics class' "drawString" method described in the first chapter -
"