未处理 JavaFX onKeyPressed 事件

标签 java events javafx fxml

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

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

关于未处理 JavaFX onKeyPressed 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33332190/

相关文章:

java - 没有参数的getConstructor

java - 如何在java中将Bystream视频转换为文件视频

java - 具有多态性和工厂类的泛型

events - 将事件处理程序绑定(bind)到多个元素 jQuery?

java - 在 JavaFX 中同时按下按键

java - 了解 getStyleClass().add() 和几行代码

java - 无法识别Java 1.7的夏令时更改

wpf - 如何从 FrameworkElement 引发 Onload/OnUnload 事件以进行单元测试?

c# - .NET 中如何实现 "Event"对象?

JavaFX - 在 crunchbang linux 中删除窗口阴影