未处理JavaFX onKeyPressed事件 [英] JavaFX onKeyPressed event not being handled

查看:93
本文介绍了未处理JavaFX onKeyPressed事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very basic JavaFX project with just an anchor pane and a label. The idea is that when you push a button on the keyboard, the label will change to the key you pressed.

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和处理程序方法.

Controller.java is even simpler. It just contains ids for the label and a handler method.

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>

当我按下一个键时,什么也没发生.没有事件处理程序被调用.我在做什么错了?

When I push a key, nothing happens. No event handler is called. What am I doing wrong?

(请注意:.fxml文件是由Scene Builder生成的.)

(Just as a side note: The .fxml file was generated by Scene Builder.)

推荐答案

似乎是焦点问题.

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

Adding a call to requestFocus() made it start printing the Event handled! :

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

这篇关于未处理JavaFX onKeyPressed事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆