我想使用动画计时器在屏幕上移动一个矩形。我想这样做,因为我想了解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);
}
}
关于java - 如何使用AnimationTimer移动节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662100/