【问题标题】:Add KeyEvent for calculator numpad in JavaFX using MVC使用 MVC 在 JavaFX 中为计算器小键盘添加 KeyEvent
【发布时间】:2017-09-22 16:56:07
【问题描述】:

我在 Eclipse 中使用 JavaFx 和 MVC 模式创建了一个简单的计算器。我想添加按键监听器,以便通过简单地按下键盘上的按钮来按下计算器的按钮。我尝试在 SceneBuilder 中添加#onKeyPress,然后在我的 Controller 类中添加一个 onKeypress 方法(内部有一些编码),但没有任何反应。您能否给出一些一般说明如何实现这样的东西?谢谢!

【问题讨论】:

  • 您需要将按键事件处理程序添加到场景中(而不是按钮)。如果将其添加到按钮中,则仅当按钮具有键盘焦点时才会调用它们。
  • 在这种情况下,onKeyReleased 似乎比 onKeypress 更好。

标签: javafx


【解决方案1】:

感谢您的 cmets。我在App.java中添加了如下代码sn-p:

scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
   @Override
   public void handle(KeyEvent event) {         
    controller.numFromKeyboard(event.getCode().toString());
   }
});

另外,我必须补充:

Parent root = loader.load();
        Controller controller = loader.getController(); 
              // The above line MUST be
              // inserted after root is loaded in order the controller of my 
              // app to be instantiated, 
              // otherwise we will get a null exception when handler will be 
              // invoked

App.java

public class App extends Application {

 //controller  = new Controller();

@Override
public void start(Stage primaryStage) {
    try {
        // Read file fxml and draw interface.
        FXMLLoader loader = new FXMLLoader(getClass()
                .getResource("/application/View.fxml"));


        Parent root = loader.load();
        Controller controller = loader.getController();
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm());
        Image icon = new Image(getClass().getResourceAsStream("/application/Assets/App.png"));
        primaryStage.getIcons().add(icon);
        primaryStage.setTitle("JavaFX Calculator by Dimitris Baltas");
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);         
        primaryStage.show();
        scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
               controller.numFromKeyboard(event.getCode().toString());
            }
        });
    } catch(Exception e) {
        e.printStackTrace();
    }
}

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

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 2020-04-17
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2015-12-07
    • 2015-03-14
    • 1970-01-01
    相关资源
    最近更新 更多