I have problems catching the KeyEvent when pressing down a key on the application pane. The files structures are as follows:
ApplicationStarter.java
package appdemo;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class ApplicationStarter extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(ApplicationStarter.class.getResource("GUI.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("Rock N' Roll");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
ApplicationControllerClass.java
package appdemo;
import javafx.fxml.FXML;
import javafx.scene.input.*;
import javafx.scene.layout.Pane;
public class ApplicationControllerClass {
@FXML
private Pane mainPane;
@FXML
void initialize(){
}
@FXML
void onKeyPressed(KeyEvent event) {
System.out.println("Key pressed on pane!");
}
@FXML
void onMouseClicked(MouseEvent event) {
System.out.println("Mouse clicked on pane!");
}
}
GUI.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.Pane?>
<Pane fx:id="mainPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onKeyPressed="#onKeyPressed" onMouseClicked="#onMouseClicked" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="appdemo.ApplicationControllerClass" />.
In ApplicationControllerClass.java, there two methods for printing the events of mouse clicking and key pressing on the console. When I run the application, the mouse clicking event prints without problem when I click on the mainPane, whereas the key pressing event does not when I press a key on mainPane.
Am I missing something? Does the method OnKeyPressed in ApplicationControllerClass.java actually catch the event?
Addendum
I also checked here and here, but could not find any upvoted, accepted or relevant answer. The problem with the current answers is that they bind an event handler method to an element in the controller class, while I wish to do this binding in GUI.fxml, as is the current case.