Java Reference
In-Depth Information
68
69 /** Enlarge the circle */
70 public void enlarge() {
71 radius++;
72 repaint();
73 }
74
75 /** Shrink the circle */
76 public void shrink() {
77 if (radius >= 1 ) radius—-;
78 repaint();
79 }
80
81 @Override
82 protected void paintComponent(Graphics g) {
83 super .paintComponent(g);
84 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius,
85
2 * radius, 2 * radius);
86 }
87 }
88 }
A listener for MouseEvent is created to handle mouse-clicked events in lines 34-42. If the
left mouse button is clicked, the circle is enlarged (lines 37-38); if the right mouse button is
clicked, the circle is shrunk (lines 39-40).
A listener for KeyEvent is created to handle key-pressed events in lines 45-53. If the UP
arrow key is pressed, the circle is enlarged (lines 48-49); if the DOWN arrow key is pressed,
the circle is shrunk (lines 50-51).
Invoking setFocusable on canvas makes canvas focusable. However, once a button is
clicked, the canvas is no longer focused. Invoking canvas.requestFocusInWindow()
(lines 22, 30) resets the focus on canvas so that canvas can listen for key events.
MouseEvent
KeyEvent
setFocusable
requestFocusInWindow()
16.18
What method do you use to get the timestamp for an action event, a mouse event, or
a key event?
Check
Point
16.19
What method do you use to get the key character for a key event?
16.20
How do you set focus on a component so it can listen for key events?
16.21
Does every key in the keyboard have a Unicode? Is a key code in the KeyEvent class
equivalent to a Unicode?
16.22
Is the keyPressed handler invoked after a key is pressed? Is the keyReleased
handler invoked after a key is released? Is the keyTyped handler invoked after any
key is typed?
16.11 Animation Using the Timer Class
A Timer is a source object that fires ActionEvent at a fixed rate.
Key
Point
Not all source objects are GUI components. The javax.swing.Timer class is a source
component that fires an ActionEvent at a predefined rate. Figure 16.18 lists some of the
methods in the class.
A Timer object serves as the source of an ActionEvent . The listeners must be instances
of ActionListener and registered with a Timer object. You create a Timer object using its
sole constructor with a delay and a listener, where delay specifies the number of milliseconds
between two action events. You can add additional listeners using the addActionListener
method and adjust the delay using the setDelay method. To start the timer, invoke the
start() method; to stop the timer, invoke the stop() method.
 
 
Search WWH ::




Custom Search