每次按下按钮时如何移动形状javafx
How to move a shape everytime a button is pressed javafx
每次按下按钮时,我都试图让这个圆圈向右移动 120 像素,但它不起作用。
double CircleX = 240;
double CircleY = 360;
public void start(Stage primaryStage) {
Group root = new Group();
//This is the circle I want to move whenever I press the button
Circle circle = new Circle(CircleX,CircleY,50);
//The button
Button MoveRight = new Button("->");
MoveRight.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) ->{
CircleX += 120;
});
root.getChildren().addAll(circle, MoveRight);
Scene scene = new Scene(root,1680,960,Color.SKYBLUE);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
我想我必须每隔几毫秒重绘一次 canvas,但我不确定如何做。有任何想法吗?提前致谢。
您忘记更新 Circle X 的位置。
为此,请将此:circle.setCenterX(CircleX);
添加到事件处理程序中。
它应该看起来像:
MoveRight.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) ->{
CircleX += 120;
circle.setCenterX(CircleX);
});
编辑:
如果要更新圆Y位置,只需添加:
circle.setCenterY(CircleY);
进入您的事件处理程序。
希望有所帮助 ;)
每次按下按钮时,我都试图让这个圆圈向右移动 120 像素,但它不起作用。
double CircleX = 240;
double CircleY = 360;
public void start(Stage primaryStage) {
Group root = new Group();
//This is the circle I want to move whenever I press the button
Circle circle = new Circle(CircleX,CircleY,50);
//The button
Button MoveRight = new Button("->");
MoveRight.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) ->{
CircleX += 120;
});
root.getChildren().addAll(circle, MoveRight);
Scene scene = new Scene(root,1680,960,Color.SKYBLUE);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
我想我必须每隔几毫秒重绘一次 canvas,但我不确定如何做。有任何想法吗?提前致谢。
您忘记更新 Circle X 的位置。
为此,请将此:circle.setCenterX(CircleX);
添加到事件处理程序中。
它应该看起来像:
MoveRight.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) ->{
CircleX += 120;
circle.setCenterX(CircleX);
});
编辑: 如果要更新圆Y位置,只需添加:
circle.setCenterY(CircleY);
进入您的事件处理程序。
希望有所帮助 ;)