Java Reference
In-Depth Information
Figure 12.3 For the
KeyTestApplet
demonstration, when the
top panel has the focus,
keystrokes are captured
and reported on the text
area.
keyTyped (KeyEvent e) method. An instance of this KeyListener can
then be added to the list of such listeners maintained by a Component subclass.
When a key press occurs, the component invokes the keyTyped() method of
all the listeners in its list. From the KeyEvent object you can then obtain the
identity of the key pressed by the user:
public void keyTyped (KeyEvent e) {
saySomething ( " got " + e.getKeyChar (), e);
}
The KeyEvent object provides the key character via the getKeyChar()
method.
The example KeyTestApplet holds an instance of a JPanel subclass called
KeyTestPanel ,which in turn holds a subpanel and a JTextArea .Weadd an
instance of a KeyAdapter to the subpanel's list of KeyListener objects. The
subpanel is made focusable so that it can receive the key events. (When the applet
runs, you should click on it and hit “tab” to put the focus on the subpanel.) The
adapter sends each KeyEvent object to the keyTyped() method whenever the
user presses a key (see Figure 12.3).
... Code in KeyTestApplet to display a KeyTestPanel
object ...
/** A JPanel class that detects key strokes on one subpanel
*anddisplays messages about them in a text area. **/
class KeyTestPanel extends JPanel
{
JTextArea fTextArea;
/** Create an interface with a text area and a blank panel.
*Keystrokes while the panel has focus will be detected
 
Search WWH ::




Custom Search