未处理 JavaFX onKeyPressed 事件

JavaFX onKeyPressed event not being handled

我有一个非常基本的 JavaFX 项目,只有一个锚定窗格和一个标签。这个想法是,当您按下键盘上的按钮时,标签将更改为您按下的键。

MainApp.java is very simple. Just load the FXML data and show it.

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Scene;
    import javafx.stage.Stage;

public class MainApp extends Application{
    public static void main (String... args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        // Set the title of the primary stage
        primaryStage.setTitle("Key Event");

        // Load the FXML data into loader
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("keyevent.fxml"));

        // Create a new scene from that FXML data
        Scene root = new Scene(loader.load());

        // Set the scene and display the stage
        primaryStage.setScene(root);
        primaryStage.show();
    }
}

Controller.java 更简单。它仅包含标签的 ID 和处理程序方法。

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;


public class Controller {

    @FXML
    Label keyInputLabel;

    @FXML
    public void handle(KeyEvent key) {
        System.out.println("Event handled!");
        keyInputLabel.setText(key.getCharacter());
    }
}

最后,.fxml 文件

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<AnchorPane focusTraversable="true" onKeyPressed="#handle" prefHeight="73.0" prefWidth="141.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
   <children>
      <Label fx:id="keyInputLabel" layoutX="68.0" layoutY="28.0" onKeyPressed="#handle" prefHeight="17.0" prefWidth="2.0" text="-" />
   </children>
</AnchorPane>

当我按下某个键时,没有任何反应。没有调用事件处理程序。我做错了什么?

(附带说明:.fxml 文件是由 Scene Builder 生成的。)

好像是焦点问题

添加对 requestFocus() 的调用使其开始打印 Event handled! :

// Create a new scene from that FXML data
Scene root = new Scene(loader.load());
root.getRoot().requestFocus();