user5339769
user5339769

Reputation:

JavaFX onKeyPressed event not being handled

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

Finally, the .fxml file

<?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?

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

Upvotes: 5

Views: 7613

Answers (1)

WillShackleford
WillShackleford

Reputation: 7008

It seems to be an issue with focus.

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

Upvotes: 7

Related Questions