我有一个非常基本的 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/