java – How to use KeyEvent in JavaFX project?

java – How to use KeyEvent in JavaFX project?

You have few issues with your code :

  1. You are using onKeyTyped instead of onKeyPressed. For more information visit this link
  2. You are most probably using java.awt.event.KeyEvent, which will not work with JavaFX events. Try to use javafx.scene.input.KeyEvent.

    The reason I came to this conclusion is because JavaFX doesnt support KeyEvent.VK_ENTER but instead have KeyCode.ENTER

A concrete example is shown below, you can use the same to convert it into FXML:

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ButtonExample extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane pane = new BorderPane();
        Button button = new Button(Press Me!);
        pane.setCenter(button);
        Scene scene = new Scene(pane, 200, 200);
        primaryStage.setScene(scene);
        primaryStage.show();

        button.setOnKeyPressed(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER) {
                    System.out.println(Enter Pressed);
                }
            }
        });
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

java – How to use KeyEvent in JavaFX project?

Leave a Reply

Your email address will not be published.