使用箭头键移动圆圈 - Java

时间:2016-09-15 04:47:06

标签: java javafx

我现在正在尝试使用JavaFX自学如何使用箭头键移动文本和项目。如果按下箭头键,我制作了一个只在舞台上移动文字的程序。

我想在我的窗格而不是文本周围移动一个圆圈。我必须使用箭头键移动我的圆圈?

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();
    }

2 个答案:

答案 0 :(得分:2)

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;
    }
});

答案 1 :(得分:0)

就个人而言,我会改变您在按键的位置。我会把它放在Pane上,因为在这个例子中它始终是焦点。除此之外,如果您不想留下最后一个,我可能必须删除并读取圈子,我不在我的计算机上,所以我无法确认,但结果代码看起来像这样。

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);

        pane.setOnKeyPressed(e -> {
            pane.getChildren().remove(circle);
            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;    
            }
            pane.getChildren().add(circle);
        });

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