Java Reference
In-Depth Information
method (lines 44-46) returns a binding property value for rate. This binding property is useful
for binding the rate in future applications in the next chapter.
L ISTING 15.18
BounceBallControl.java
1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.input.KeyCode;
5
6 public class BounceBallControl extends Application {
7 @Override // Override the start method in the Application class
8
public void start(Stage primaryStage) {
9
BallPane ballPane = new BallPane(); // Create a ball pane
create a ball pane
10
11 // Pause and resume animation
12 ballPane.setOnMousePressed(e -> ballPane.pause());
13 ballPane.setOnMouseReleased(e -> ballPane.play());
14
15 // Increase and decrease animation
16 ballPane.setOnKeyPressed(e -> {
17
pause animation
resume animation
if (e.getCode() == KeyCode.UP) {
18
ballPane.increaseSpeed();
increase speed
19 }
20
else if (e.getCode() == KeyCode.DOWN) {
21
ballPane.decreaseSpeed();
decrease speed
22 }
23 });
24
25 // Create a scene and place it in the stage
26 Scene scene = new Scene(ballPane, 250 , 150 );
27 primaryStage.setTitle( "BounceBallControl" ); // Set the stage title
28 primaryStage.setScene(scene); // Place the scene in the stage
29 primaryStage.show(); // Display the stage
30
31 // Must request focus after the primary stage is displayed
32 ballPane.requestFocus();
33 }
34 }
request focus on pane
The BounceBallControl class is the main JavaFX class that extends Applicaiton to
display the ball pane with control functions. The mouse-pressed and mouse-released handlers
are implemented for the ball pane to pause the animation and resume the animation (lines 12
and 13). When the UP arrow key is pressed, the ball pane's increaseSpeed() method is
invoked to increase the ball's movement (line 18). When the DOWN arror key is pressed, the
ball pane's decreaseSpeed() method is invoked to reduce the ball's movement (line 21).
Invoking ballPane.requestFocus() in line 32 sets the input focus to ballPane .
15.24
How does the program make the ball moving?
Check
15.25
How does the code in Listing 15.17 BallPane.java change the direction of the ball
movement?
Point
15.26
What does the program do when the mouse is pressed on the ball pane? What does
the program do when the mouse is released on the ball pane?
15.27
If line 32 in Listing 15.18 BounceBallControl.java is not in the program, what would
happen when you press the UP or the DOWN arrow key?
15.28
If line 23 is not in Listing 15.17, what would happen?
 
Search WWH ::




Custom Search