Java Reference
In-Depth Information
29
30
public
MovingMessagePanel(String message) {
31
this
.message = message;
set message
32
33
// Start timer for animation
timer.start();
34
35
36
// Control animation speed using mouse buttons
37
this
.addMouseListener(
new
MouseAdapter() {
38 @Override
39
start timer
mouse listener
public void
mouseClicked(MouseEvent e) {
40
int
delay = timer.getDelay();
41
if
(e.getButton() == MouseEvent.BUTTON1)
timer.setDelay(delay >
10
? delay -
10
:
0
);
42
43
else if
(e.getButton() == MouseEvent.BUTTON3)
timer.setDelay(delay <
50000
? delay +
10
:
50000
);
44
45 }
46 });
47 }
48
49 @Override
/** Paint the message */
50
protected void
paintComponent(Graphics g) {
51
super
.paintComponent(g);
52
53
if
(xCoordinate > getWidth()) {
54 xCoordinate =
-20
;
55 }
56 xCoordinate +=
5
;
57 g.drawString(message, xCoordinate, yCoordinate);
58 }
59
60
61 @Override
62
public void
actionPerformed(ActionEvent e) {
63 repaint();
64 }
65 }
66 }
67 }
reset
x
-coordinate
move message
class
TimerListener
implements
ActionListener {
listener class
event handler
repaint
Two instances of
MovingMessagePanel
are created to display two messages (lines 9-10).
The
MovingMessagePanel
class extends
JPanel
to display a message (line 24). 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.
An inner class listener is defined in line 60 to listen for
ActionEvent
from a timer. Line
28 creates a
Timer
for the listener, and the timer is started in line 34. The timer fires an
ActionEvent
every 1 second initially, and the listener responds in line 62 to repaint the
panel. When a panel is painted, its
x
-coordinate is increased (line 56), so the message is dis-
played to the right. When the
x
-coordinate exceeds the bound of the panel, it is reset to
-20
(line 54), so the message continues moving from left to right circularly.
A mouse listener is registered with the panel to listen for the mouse click event (lines
37-46). When the left mouse button is clicked, a new reduced delay time is set for the timer
(lines 41-42). When the right mouse button is clicked, a new increased delay time is set for
the timer (lines 43-44). The minimum delay time is
0
and the maximum can be
Integer.MAX_VALUE
, but it is set to
50000
in this program (line 44).
In Section 13.9, Case Study: The
StillClock
Class, you drew a
StillClock
to show
the current time. The clock does not tick after it is displayed. What can you do to make the