Java Reference
In-Depth Information
37
if
(y <
0
|| y > getHeight())
38 dy *=
-1
;
39
40
// Adjust ball position
41 x += dx;
42 y += dy;
43 g.fillOval(x - radius, y - radius, radius *
2
, radius *
2
);
44 }
45
46
public void
suspend() {
47 timer.stop();
// Suspend timer
48 }
49
50
public void
resume() {
51 timer.start();
// Resume timer
52 }
53
54
public void
setDelay(
int
delay) {
55
this
.delay = delay;
56 timer.setDelay(delay);
57 }
58 }
The use of
Timer
to control animation was introduced in Section 16.11, Animation Using the
Timer
Class.
Ball
extends
JPanel
to display a moving ball. The timer listener implements
ActionListener
to listen for
ActionEvent
(line 21). Line 10 creates a
Timer
for a
Ball
.
The timer is started in line 18 when a
Ball
is constructed. The timer fires an
ActionEvent
at a fixed rate. The listener responds in line 24 to repaint the ball to animate ball movement.
The center of the ball is at (
x
,
y
), which changes to (
x + dx
,
y + dy
) on the next display
(lines 41-42). When the ball is out of the horizontal boundary, the sign of
dx
is changed (from
positive to negative, or vice versa) (lines 35-36). This causes the ball to change its horizontal
movement direction. When the ball is out of the vertical boundary, the sign of
dy
is changed
(from positive to negative, or vice versa) (lines 37-38). This causes the ball to change its ver-
tical movement direction. The
suspend
and
resume
methods (lines 46-52) can be used to
stop and start the timer. The
setDelay(int)
method (lines 54-57) sets a new delay.
L
ISTING
18.8
BallControl.java
1
import
javax.swing.*;
2
import
java.awt.event.*;
3
import
java.awt.*;
4
5
public class
BallControl
extends
JPanel {
6
private
Ball ball =
new
Ball();
7
8
9
10
11
public
BallControl() {
12
// Group buttons in a panel
13 JPanel panel =
new
JPanel();
14 panel.add(jbtSuspend);
15 panel.add(jbtResume);
16
17
// Add ball and buttons to the panel
18 ball.setBorder(
new
javax.swing.border.LineBorder(Color.red));
19 jsbDelay.setOrientation(JScrollBar.HORIZONTAL);
20 ball.setDelay(jsbDelay.getMaximum());
21 setLayout(
new
BorderLayout());
private
JButton jbtSuspend =
new
JButton(
"Suspend"
);
button
private
JButton jbtResume =
new
JButton(
"Resume"
);
private
JScrollBar jsbDelay =
new
JScrollBar();
scroll bar
create UI