JavaFX KeyEvent setOnKeyPressed仅适用于按钮?不适用于圈

时间:2017-08-11 15:50:38

标签: java javafx keyevent

我有一个代码可以使用按钮但不能使用圆圈。

我想要做的是在用户按下键盘上的按钮后执行某些操作。以下代码仅适用于按钮。只需将圆圈改为按钮(两次)即可看到它的工作原理。用于其他任何事情的代码不合适吗?

提前致谢。

代码:

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class ButtonExample extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane pane = new BorderPane();
        Button button = new Button("Press Me!");



        //circle
        Circle circle = new Circle(); 

      //Setting the position of the circle 
      circle.setCenterX(300.0f); 
      circle.setCenterY(135.0f); 

      //Setting the radius of the circle 
      circle.setRadius(25.0f);  

      //Setting the color of the circle 
      circle.setFill(Color.BROWN); 

      //Setting the stroke width of the circle 
      circle.setStrokeWidth(20);    


                pane.setCenter(circle); // JUST CHANGE HERE (circle) to (button) to make it work
        Scene scene = new Scene(pane, 200, 200);
        primaryStage.setScene(scene);
        primaryStage.show();

        circle.setOnKeyPressed(new EventHandler<KeyEvent>() { /////and HERE

            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER) {
                    System.out.println("Enter Pressed");
                }
            }
        });



    }



    public static void main(String[] args) {
        launch(args);
    }
}

0 个答案:

没有答案