我想使用AnimationTimer在屏幕上移动一个矩形。我想这样做,因为我想学习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);
}
}
答案 0 :(得分:3)
这是一个简单的示例(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);
}
}