如何使用时间轴正确启动javafx动画?

时间:2017-11-05 00:36:47

标签: animation javafx timeline

我正在尝试使用从本网站收集的代码制作一个可以反弹圈子的应用程序。当我现在点击时 - 它会创建一个似乎在适当位置振动并且不会从边界反弹的圆圈。

这是代码帽子,我感谢我的问题

@FXML
private AnchorPane anchorPane;
@FXML
private Label ballCountLabel;

public int ballCount = 0;
public int mouseClick = 0;

Circle[] balls = new Circle[1000];

@Override
public void initialize(URL url, ResourceBundle rb) {
    pane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
    AnchorPane.setTopAnchor(pane, 0.0);
    AnchorPane.setLeftAnchor(pane, 0.0);
    AnchorPane.setTopAnchor(pane, 0.0);
    AnchorPane.setRightAnchor(pane, 0.0);
}

@FXML
private void mouseAddBall(MouseEvent event) throws Exception {

    balls[mouseClick] = new Circle(15, Color.BLANCHEDALMOND);
    balls[mouseClick].relocate(event.getSceneX(), event.getSceneY());
    pane.getChildren().add(balls[mouseClick]);
    ballCount++;
    ballCountLabel.setText("Ball Count: " + ballCount);
    addBallMovement(balls[mouseClick]);
    mouseClick++;
}
public void addBallMovement(Circle b){

    final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {

        double deltaX = 3;
        double deltaY = 3;

        @Override
        public void handle(ActionEvent t) {
            b.setLayoutX(b.getLayoutX() + deltaX);
            b.setLayoutY(b.getLayoutY() + deltaY);

            final Bounds bounds = pane.getBoundsInParent();

            final boolean atRightBorder = b.getLayoutX() >= (bounds.getMaxX() - b.getRadius());
            final boolean atLeftBorder = b.getLayoutX() <= (bounds.getMinX() + b.getRadius());
            final boolean atBottomBorder = b.getLayoutY() >= (bounds.getMaxY() - b.getRadius());
            final boolean atTopBorder = b.getLayoutY() <= (bounds.getMinY() + b.getRadius());

            if (atRightBorder || atLeftBorder) {
                deltaX *= -1;
            }
            if (atBottomBorder || atTopBorder) {
                deltaY *= -1;
            }
        }
    }));
    loop.setCycleCount(Timeline.INDEFINITE);
    loop.play();

1 个答案:

答案 0 :(得分:0)

我将Ball更改为Circle以测试您的代码。在向当前球添加移动之前,您将更改为balls数组中的下一个球。这可能会给你一个NullPointerException

更改

balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(), 
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
addBallMovement(balls[mouseClick]);  //<--You want to move the current ball. This code needs to be before mouseClick++

要:

balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(), 
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
addBallMovement(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);