Created
December 29, 2015 23:55
-
-
Save abd3lraouf/7fd57e2f8daad755f0bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.animation.*; | |
import javafx.beans.property.*; | |
import javafx.scene.layout.*; | |
import javafx.scene.paint.*; | |
import javafx.scene.shape.*; | |
import javafx.util.*; | |
public class BallPane extends Pane { | |
public final double radius = 20; | |
private double x = radius, y = radius; | |
private double dx = 1, dy = 1; | |
private Circle circle = new Circle(x, y, radius); | |
private Timeline animation; | |
public BallPane() { | |
circle.setFill(Color.GREEN); // Set ball color | |
getChildren().add(circle); // Place a ball into this pane | |
// Create an animation for moving the ball | |
animation = new Timeline( | |
new KeyFrame(Duration.millis(50), e -> moveBall())); | |
animation.setCycleCount(Timeline.INDEFINITE); | |
animation.play(); // Start animation | |
} | |
public void play() { | |
animation.play(); | |
} | |
public void pause() { | |
animation.pause(); | |
} | |
public void increaseSpeed() { | |
animation.setRate(animation.getRate() + 0.1); | |
} | |
public void decreaseSpeed() { | |
animation.setRate( | |
animation.getRate() > 0 ? animation.getRate() - 0.1 : 0); | |
} | |
public DoubleProperty rateProperty() { | |
return animation.rateProperty(); | |
} | |
protected void moveBall() { | |
// Check boundaries | |
if (x < radius || x > getWidth() - radius) { | |
dx *= -1; // Change ball move direction | |
} | |
if (y < radius || y > getHeight() - radius) { | |
dy *= -1; // Change ball move direction | |
} | |
// Adjust ball position | |
x += dx; | |
y += dy; | |
circle.setCenterX(x); | |
circle.setCenterY(y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment