Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Handling User Events 205

. void keyTyped(KeyEvent)—A method called after a key has been
pressed and released


Each of these has a KeyEventobject as an argument, which has methods to
call to find out more about the event. Call the getKeyChar()method to
find out which key was pressed. This key is returned as a charvalue, and
it only can be used with letters, numbers, and punctuation.


To monitor any key on the keyboard, including Enter, Home, Page Up, and
Page Down, you can call getKeyCode()instead. This method returns an
integer value representing the key. You then can call getKeyText()with
that integer as an argument to receive a Stringobject containing the name
of the key (such as Home, F1, and so on).


Listing 15.1 contains a Java application that draws the most recently pressed
key in a label by using the getKeyChar()method. The application imple-
ments the KeyListenerinterface, so there are keyTyped(), keyPressed(),
and keyReleased()methods in the class. The only one of these that does
anything is keyTyped()in Lines 22–25. Create a new Java file called
KeyViewer, enter the listing in NetBeans’ source editor, and save the file.


LISTING 15.1 The Full Text of KeyViewer.java
1: importjavax.swing.;
2: importjava.awt.event.
;
3: importjava.awt.*;
4:
5: public classKeyViewer extendsJFrame implementsKeyListener {
6: JTextField keyText= new JTextField(80);
7: JLabel keyLabel= new JLabel(“Press any key in the text field.”);
8:
9: KeyViewer() {
10: super(“KeyViewer”);
11: setLookAndFeel();
12: setSize(350, 100);
13: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14: keyText.addKeyListener(this);
15: BorderLayout bord = new BorderLayout();
16: setLayout(bord);
17: add(keyLabel, BorderLayout.NORTH);
18: add(keyText, BorderLayout.CENTER);
19: setVisible(true);
20: }
21:
22: public voidkeyTyped(KeyEvent input) {
23: charkey = input.getKeyChar();
24: keyLabel.setText(“You pressed “ + key);
25: }

Free download pdf