Java Reference
In-Depth Information
Here are the major steps to write this program:
1. Define a subclass of
Pane
named
BallPane
to display a ball bouncing, as shown in
ListingĀ 15.17.
2. Define a subclass of
Application
named
BounceBallControl
to control the bounc-
ing ball with mouse actions, as shown in ListingĀ 15.18. The animation pauses when the
mouse is pressed and resumes when the mouse is released. Pressing the UP and DOWN
arrow keys increases/decreases animation speed.
The relationship among these classes is shown in FigureĀ 15.23.
javafx.scene.layout.Pane
javafx.application.Application
1
1
BallPane
BounceBallControl
-x: double
-y: double
-dx: double
-dy: double
-radius: double
-circle: Circle
-animation: Timeline
+BallPane()
+play(): void
+pause(): void
+increaseSpeed(): void
+decreaseSpeed(): void
+rateProperty(): DoubleProperty
+moveBall(): void
F
IGURE
15.23
BounceBallControl
contains
BallPane
.
L
ISTING
15.17
BallPane.java
1
import
javafx.animation.KeyFrame;
2
import
javafx.animation.Timeline;
3
import
javafx.beans.property.DoubleProperty;
4
import
javafx.scene.layout.Pane;
5
import
javafx.scene.paint.Color;
6
import
javafx.scene.shape.Circle;
7
import
javafx.util.Duration;
8
9
public class
BallPane
extends
Pane {
10
public final double
radius =
20
;
11
private double
x = radius, y = radius;
12
private double
dx =
1
, dy =
1
;
13
private
Circle circle =
new
Circle(x, y, radius);
14
private
Timeline animation;
15
16
public
BallPane() {
17 circle.setFill(Color.GREEN);
// Set ball color
18 getChildren().add(circle);
// Place a ball into this pane
Search WWH ::
Custom Search