Question: Listing 15.17 BallPane.java using a thread to animate bouncing ball movements. Listing 1 import javafx.animation.KeyFrame; 2 import javafx.animation.Timeline; 3 import javafx.beans.property.DoubleProperty; 4 import javafx.scene.layout.Pane; 5
Listing 15.17 BallPane.java using a thread to animate bouncing ball movements.
Listing


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; 9 public class BallPane extends Pane { public final double radius = 20; 10 private double x = radius, y = radius; 11 private double dx = 1, dy = 1; 12 13 private Circle circle = new Circle(x, y, radius); private Timeline animation; 14 15 16 17 18 public BallPane() { circle.setFili(Color.GREEN); // Set ball color getChildren().add(circle); // Place a ball into this pane 19 // Create an animation for moving the ball animation = new Timeline( new KeyFrame (Duration.millis(50), e -> moveBall())); animation.setCycleCount (Timeline. INDEFINITE); animation.playO; // Start animation 20 21 22 23 24 25 26 27 public void play() { animation.play(); 28 29 public void pause() { animation.pause(); 31 32 33 34 public void increaseSpeed () { animation.setRate(animation.getRate() + 0.1); 35 36 37 38 39 public void decreaseSpeed () { animation.setRate( animation.getRate() > 0 ? animation.getRate() - 0.1 : 0); 40 41 42 43 44 45 public DoubleProperty rateProperty() { return animation.rateProperty(); 46 47 protected void moveBall() { // Check boundaries if (x < radius || x > getWidth) - radius) { dx *= -1; // hange ball move direction 48 49 50 51 52 if (y < radius || y > getHeight() - radius) { dy *= -1; // Change ball move direction 53 54 55 56 // Adjust ball position x += dx; y += dy; circle.setCenterX(x); circle.setCenterY(y); 57 58 59 60 61 62 63 } ANNN NNNONNNNmmm
Step by Step Solution
3.42 Rating (155 Votes )
There are 3 Steps involved in it
Program Plan Create add method so that adds one ball to the list when the user clicks on 1 button an... View full answer
Get step-by-step solutions from verified subject matter experts
