Java Reference
In-Depth Information
29
private int
x =
100
;
30
private int
y =
100
;
31
private char
keyChar =
'A'
;
// Default key
32
33
public
KeyboardPanel() {
34 addKeyListener(
35 @Override
36
37
new
KeyAdapter() {
register listener
public void
keyPressed(KeyEvent e) {
override handler
switch
(e.getKeyCode()) {
38
case
KeyEvent.VK_DOWN: y +=
10
;
break
;
39
case
KeyEvent.VK_UP: y -=
10
;
break
;
40
case
KeyEvent.VK_LEFT: x -=
10
;
break
;
41
case
KeyEvent.VK_RIGHT: x +=
10
;
break
;
42
default
: keyChar = e.getKeyChar();
get the key pressed
43 }
44
45 repaint();
46 }
47 );
48 }
49
50 @Override
/** Draw the character */
51
repaint
}
protected void
paintComponent(Graphics g) {
52
super
.paintComponent(g);
53
54 g.setFont(
new
Font(
"TimesRoman"
, Font.PLAIN,
24
));
55 g.drawString(String.valueOf(keyChar), x, y);
56 }
57 }
58 }
redraw character
The
KeyboardPanel
class extends
JPanel
to display a character (line 28). This class is
defined as an inner class inside the main class, because it is used only in this class. Further-
more, the inner class is defined as static, because it does not reference any instance members
of the main class.
Because the program gets input from the keyboard, it listens for
KeyEvent
and extends
KeyAdapter
to handle key input (line 34).
When a key is pressed, the
keyPressed
handler is invoked. The program uses
e.getKeyCode()
to obtain the key code and
e.getKeyChar()
to get the character for the
key. When a nonarrow key is pressed, the character is displayed (line 42). When an arrow key
is pressed, the character moves in the direction indicated by the arrow key (lines 38-41).
Only a focused component can receive
KeyEvent
. To make a component focusable, set its
focusable
property to
true
(line 14).
Every time the component is repainted, a new font is created for the
Graphics
object in
line 54. This is not efficient—it would be better to create the font once as a data field.
We can now add more control for our
ControlCircle
example in Listing 16.3 to
increase/decrease the circle radius by clicking the left/right mouse button or by pressing the
UP and DOWN arrow keys. The new program is given in Listing 16.10.
focusable
efficient?
L
ISTING
16.10
ControlCircleWithMouseAndKey.java
1
import
javax.swing.*;
2
import
java.awt.*;
3
import
java.awt.event.*;
4
5
public class
ControlCircleWithMouseAndKey
extends
JFrame {
6
private
JButton jbtEnlarge =
new
JButton(
"Enlarge"
);
7
private
JButton jbtShrink =
new
JButton(
"Shrink"
);