java - 如何使用AnimationTimer移动节点?

标签 java javafx

我想使用动画计时器在屏幕上移动一个矩形。我想这样做,因为我想了解AnimationTimer是如何工作的,这样我就可以用它制作一个游戏。我目前在这样做时遇到问题。

public class FXTimer extends Application {


    @Override
    public void start(Stage primaryStage) {

        Rectangle rect = new Rectangle(1000,100,100,100);

        AnimationTimer timer = new AnimationTimer(){
            @Override
            public void handle(long now) {
                rect.relocate(rect.getLayoutX()-10, 100);
            }      
        };

        //root.getChildren().addAll(rect);
        timer.start();


        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(new Scene(new Group(rect),1000,1000));
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

最佳答案

这是一个简单的示例(mvce:复制、粘贴、运行)。请注意评论:

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class FXTimer extends Application {

    @Override
    public void start(Stage primaryStage) {

        Rectangle rect = new Rectangle(0,0,10,10); //make is small so you can see it move
        rect.setFill(Color.BLUE); //set distinc color so you can see it move
        AnimationTimer timer = new AnimationTimer(){
            @Override
            public void handle(long now) {
                rect.setTranslateX(rect.getTranslateX()+ 1);
                //rect.relocate(rect.getLayoutX() +10, 100); //relocate does not change translateX or translateY
            }
        };

        timer.start();

        primaryStage.setTitle("AnimationTimer Demo");
        primaryStage.setScene(new Scene(new Group(rect),300,100));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here

关于java - 如何使用AnimationTimer移动节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662100/

相关文章:

java - 如何将文本区域/字段与怪物动画以及代码同步?

java - 触发事件时自发的 NullPointerExceptions

java - 重新绘制没有做任何事情

version - Java 版本的差异

java - 如何获取非 case 类的构造函数参数的默认值?

Java Web 启动问题

java - fx :id and id: in JavaFX? 和有什么区别

java - JavaFX 8中如何在鼠标拖动事件位置时获取节点?

javascript - JavaFx WebView 视频 : onended event

java - Subclipse 合并问题 - 试运行与合并结果不匹配