Java Reference
In-Depth Information
19
20
// Create an animation for moving the ball
21 animation =
new
Timeline(
22
create animation
new
KeyFrame(Duration.millis(
50
), e -> moveBall()));
23
animation.setCycleCount(Timeline.INDEFINITE);
keep animation running
start animation
24
animation.play();
// Start animation
25 }
26
27
public void
play() {
28 animation.play();
29 }
30
31
public void
pause() {
32 animation.pause();
33 }
34
35
play animation
pause animation
public void
increaseSpeed() {
36
animation.setRate(animation.getRate() +
0.1
);
increase animation rate
37 }
38
39
public void
decreaseSpeed() {
40 animation.setRate(
41 animation.getRate() >
0
? animation.getRate() -
0.1
:
0
);
42 }
43
44
decrease animation rate
public
DoubleProperty rateProperty() {
45
return
animation.rateProperty();
46 }
47
48
protected void
moveBall() {
49
// Check boundaries
50
if
(x < radius || x > getWidth() - radius) {
51
dx *=
-1
;
// Change ball move direction
change horizontal direction
52 }
53
if
(y < radius || y > getHeight() - radius) {
54
dy *=
-1
;
// Change ball move direction
change verticaal direction
55 }
56
57
// Adjust ball position
58 x += dx;
59 y += dy;
60 circle.setCenterX(x);
61 circle.setCenterY(y);
62 }
63 }
set new ball position
BallPane
extends
Pane
to display a moving ball (line 9). An instance of
Timeline
is
created to control animation (lines 21 and 22). This instance contains a
KeyFrame
object that
invokes the
moveBall()
method at a fixed rate. The
moveBall()
method moves the ball to
simulate animation. The center of the ball is at (
x
,
y
), which changes to (
x + dx
,
y + dy
) on
the next move (lines 58-61). When the ball is out of the horizontal boundary, the sign of
dx
is
changed (from positive to negative or vice versa) (lines 50-52). 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 53-55). This causes the ball to change
its vertical movement direction. The
pause
and
play
methods (lines 27-33) can be used to
pause and resume the animation. The
increaseSpeed()
and
decreaseSpeed()
methods
(lines 35-42) can be used to increase and decrease animation speed. The
rateProperty()
Search WWH ::
Custom Search