chris chris - 2 months ago 18
Java Question

Move a circle using arrow keys - Java

I'm experimenting with JavaFX right now teaching myself how to move text and items using the arrow keys. I made a program that simply moves text around the stage if an arrow key is pressed down.

I would like to make a circle move around my pane instead of text. What changes must I make to move my circle using the arrow keys?

public void start(Stage primaryStage) {
Pane pane = new Pane();

int dx = 50;
int dy = 50;
int radius = 125;

Circle circle = new Circle(radius,dx,dy);
Text text = new Text(20,20,"HI");
circle.setFill(Color.WHITE);
circle.setStroke(Color.BLACK);

pane.getChildren().addAll(circle, text);

circle.setOnKeyPressed(e -> {
switch(e.getCode()) {
case DOWN: text.setY(text.getY() + 10);
break;
case UP: text.setY(text.getY() - 10);
break;
case LEFT: text.setX(text.getX() - 10);
break;
case RIGHT: text.setX(text.getX() + 10);
break;
default:
if(Character.isLetterOrDigit(e.getText().charAt(0)))
text.setText(e.getText());
break;
}
});

Scene scene = new Scene(pane, 250, 200);
primaryStage.setTitle("Arrow Keys");
primaryStage.setScene(scene);
primaryStage.show();

text.requestFocus();
}

Answer
scene.setOnKeyPressed(e -> {
    switch (e.getCode()) {
    case DOWN:
        circle.setCenterY(circle.getCenterY() + 10);
        break;
    case UP:
        circle.setCenterY(circle.getCenterY() - 10);
        break;
    case LEFT:
        circle.setCenterX(circle.getCenterX() - 10);
        break;
    case RIGHT:
        circle.setCenterX(circle.getCenterX() + 10);
        break;
    }
});
Comments