FAQ 3c
Updated: 1/7/00
>>>>>> How do I respond to the Mouse?
=====================================
The Applet has several keyboard functions that you can overwrite.
These functions are inherited from the Component class.
(Applet extends Container which extends Component).
public boolean keyDown(Event e,int key);
public boolean keyUp(Event e,int key);
Here is a sample applet that uses the mouseMove() function:
// 'KeyApplet.java' code file
import java.applet.*;
import java.awt.*;
class KeyApplet extends Applet {
String myString;
KeyApplet(){
myString = "";
}
public void paint(Graphics g){
g.drawString("My String="+myString,10,20);
}
public boolean keyDown(Event e,int key){
myString += (char)key;
repaint(); // redraw the screen
return false; // default response
}
}
As you can see, this applet will add the key you hit to the end of a string,
then display it. This program won't work if your applet doesn't have the focus.
If you need to, you can click on your applet to give it the focus.
The value returned by the function indicates if the component's (KeyApplet's)
parent should recieve the event. The value TRUE means that your function has
consumed the event. The parent won't recieve the event in this case. The value
FALSE means that the event still exists and should move up the component tree.
see FAQ_2d to learn more about parents and component trees.
>>>>>> Advanced Key Handling
============================
The method described above is the version 1.0 method. It still works, but has been
deprecated (declared old, someday won't be supported). The new method is to
use a KeyListener.
KeyListener is an interface, not a class. You can't extend an interface like
you can a class. You have to create a class, then implement the interface.
When you implement an interface, there will be some functions that you must write.
In the case of the KeyListener, there are three functions you have to include:
class MyKeyHandler implements KeyListener {
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
After you have your KeyListener, you need to tell the component (in this case the applet)
to talk to the KeyListener. You do this with the addKeyListener() function. You can
add a KeyListener to any component - a button, a textfield, etc. But it's usually only
useful to add it to the applet.
Here is the same applet as before, with an sub-class to handle key events:
// 'KeyApplet.java' code file
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class KeyApplet extends Applet {
String myString="";
KeyApplet(){}
public void init(){
addKeyListener(new MyKeyHandler());
}
public void paint(Graphics g){
g.drawString("My String="+myString,10,20);
}
class MyKeyHandler implements KeyListener {
public void keyPressed(KeyEvent e){
myString += e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
}