Java Reference
In-Depth Information
25 Button btSubtract = new Button( "-" );
26 HBox hBox = new HBox( 10 );
27 hBox.getChildren().addAll(btAdd, btSubtract);
28 hBox.setAlignment(Pos.CENTER);
29
30
add buttons to HBox
// Add or remove a ball
31
btAdd.setOnAction(e -> ballPane.add());
add a ball
remove a ball
32
btSubtract.setOnAction(e -> ballPane.subtract());
33
34
// Pause and resume animation
35
ballPane.setOnMousePressed(e -> ballPane.pause());
pause animation
resume animation
36
ballPane.setOnMouseReleased(e -> ballPane.play());
37
38 // Use a scroll bar to control animation speed
39 ScrollBar sbSpeed = new ScrollBar();
40 sbSpeed.setMax( 20 );
41 sbSpeed.setValue( 10 );
42
create a scroll bar
ballPane.rateProperty().bind(sbSpeed.valueProperty());
bind animation rate
43
44 BorderPane pane = new BorderPane();
45 pane.setCenter(ballPane);
46 pane.setTop(sbSpeed);
47 pane.setBottom(hBox);
48
49 // Create a scene and place the pane in the stage
50 Scene scene = new Scene(pane, 250 , 150 );
51 primaryStage.setTitle( "MultipleBounceBall" ); // Set the stage title
52 primaryStage.setScene(scene); // Place the scene in the stage
53 primaryStage.show(); // Display the stage
54 }
55
56
private class MultipleBallPane extends Pane {
57
private Timeline animation;
58
59 public MultipleBallPane() {
60 // Create an animation for moving the ball
61 animation = new Timeline(
62 new KeyFrame(Duration.millis( 50 ), e -> moveBall()));
63 animation.setCycleCount(Timeline.INDEFINITE);
64
animation.play(); // Start animation
65 }
66
67 public void add() {
68 Color color = new Color(Math.random(),
69 Math.random(), Math.random(), 0.5 );
70
getChildren().add( new Ball( 30 , 30 , 20 , color));
add a ball to pane
71 }
72
73 public void subtract() {
74 if (getChildren().size() > 0 ) {
75 getChildren().remove(getChildren().size() - 1 );
76 }
77 }
78
79 public void play() {
80 animation.play();
81 }
82
83
remove a ball
public void pause() {
 
Search WWH ::




Custom Search