Reputation: 13
I'm trying to get this circle to move by 120 pixels to the right each time I press a button, but it's not working.
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);
}
I think I have to redraw the canvas every couple milliseconds, but I'm not sure how. Any Ideas? Thanks in advance.
Upvotes: 1
Views: 217
Reputation: 38
You forget to update Circle X position.
To do it, add this: circle.setCenterX(CircleX);
into event handler.
It should look like:
MoveRight.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) ->{
CircleX += 120;
circle.setCenterX(CircleX);
});
Edit: If you want update circle Y position, just add:
circle.setCenterY(CircleY);
Into your event handler.
Hope helps ;)
Upvotes: 2