首页 文章

JavaFX onKeyPressed事件未被处理

提问于
浏览
1

我有一个非常基本的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生成的 . )

1 回答

  • 2

    这似乎是一个焦点问题 .

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

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

相关问题