Here, ml is a reference to the object receiving mouse events, and mml is a reference to the
object receiving mouse motion events. In this program, the same object is used for both.
The applet then implements all of the methods defined by the MouseListener and
MouseMotionListener interfaces. These are the event handlers for the various mouse
events. Each method handles its event and then returns.
Handling Keyboard Events
To handle keyboard events, you use the same general architecture as that shown in the
mouse event example in the preceding section. The difference, of course, is that you will
be implementing the KeyListener interface.
Before looking at an example, it is useful to review how key events are generated. When
a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( )
event handler. When the key is released, a KEY_RELEASED event is generated and the
keyReleased( ) handler is executed. If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the user
presses a key, at least two and often three events are generated. If all you care about are actual
characters, then you can ignore the information passed by the keypress and release events.
However, if your program needs to handle special keys, such as the arrow or function keys,
then it must watch for them through the keyPressed( ) handler.
The following program demonstrates keyboard input. It echoes keystrokes to the applet
window and shows the pressed/released status of each key in the status window.
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home