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 doesn't 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);
    }
}
Answer from ItachiUchiha on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › javafx › api › javafx › scene › input › KeyEvent.html
KeyEvent (JavaFX 8)
2 weeks ago - javafx.scene.input.KeyEvent · All Implemented Interfaces: Serializable, Cloneable · public final class KeyEvent extends InputEvent · An event which indicates that a keystroke occurred in a Node. This event is generated when a key is pressed, released, or typed.
🌐
OpenJFX
openjfx.io › javadoc › 21 › javafx.graphics › javafx › scene › input › class-use › KeyEvent.html
Uses of Class javafx.scene.input.KeyEvent (JavaFX 21)
final ObjectProperty<EventHandler<? super KeyEvent>> ... Defines a function to be called when some Node of this Scene has input focus and a key has been typed. Method parameters in javafx.scene with type arguments of type KeyEvent
🌐
Oracle
docs.oracle.com › javafx › 2 › api › javafx › scene › input › KeyEvent.html
KeyEvent (JavaFX 2.2)
javafx.scene.input.KeyEvent · All Implemented Interfaces: java.io.Serializable, java.lang.Cloneable · public class KeyEvent extends InputEvent · An event which indicates that a keystroke occurred in a Node. This event is generated when a key is pressed, released, or typed.
🌐
Kensoft PH
kensoftph.com › key-event-in-javafx-tutorial-for-beginners
How to use the Key Event in JavaFX | 100% Best for beginners
The lower-level event are KEY_PRESSED AND KEY_RELEASED since they will occur with a key press and key release. The KEY_TYPED event is the higher-level event, it occurs when a Unicode character is typed.
Published   November 28, 2021
🌐
Coderanch
coderanch.com › t › 708545 › java › javafx-globally-listen-keyboard-events
javafx globally listen keyboard events (JavaFX forum at Coderanch)
April 11, 2019 - Short of rewriting javafx.scene.control.Dialog, I'm not sure what to do. All things are lawful, but not all things are profitable. reply reply · Bookmark Topic Watch Topic · New Topic · Boost this thread! Similar Threads · keyboard event while drag and drop · Alt + Tab, Ctl + Esc · KeyListener Problem · Getting multiple characters in a KeyEventDispatcher ·
Find elsewhere
🌐
JustAnswer
justanswer.com › computer-programming › mwfez-javafx-event-handling-keyevent-keyevents-explain.html
JavaFX Event Handling: KeyEvent and KeyEvents: Explain how to handle keyboard events like key presses and key releases
September 3, 2023 - In JavaFX, use setOnKeyPressed and setOnKeyReleased event handlers to manage keyboard input. KeyEvent captures key codes and modifiers, enabling precise control. Ensure your scene or node is focusable and has focus to receive events.
🌐
HWS Math
math.hws.edu › javanotes › source › chapter6 › KeyboardEventDemo.java
KeyboardEventDemo.java
Pane root = new Pane(canvas); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Keyboard Event Demo"); stage.setResizable(false); scene.setOnKeyPressed( e -> keyPressed(e) ); scene.setOnKeyTyped( e -> keyTyped(e) ); scene.setOnKeyReleased( e -> keyReleased(e) ); stage.show(); } //--------------- Key event handling methods -------------------- private void keyTyped(KeyEvent evt) { String ch = evt.getCharacter(); System.out.println("Char Typed: " + ch); // for testing switch (ch) { // (Note: Old switch statement syntax used here, just as an example.) case "r": squareColor = C
🌐
Java2s
java2s.com › ref › java › javafx-keyevent-handle-key-event-on-pane.html
JavaFX KeyEvent handle key event on Pane
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.shape.Line; import javafx.stage.Stage; public class Main extends Application { Pane pane = new Pane(); double width = 400; double height = 400; double cX = width / 2; double cY = height / 2; @Override/*from www .
🌐
Blogger
drranurekha.blogspot.com › 2024 › 11 › event-handling.html
Dr R Anurekha: Event Handling
public void handle(KeyEvent ke) { String str = "Key Released : "+ke.getCode(); respText.setText(str.toString()); } } ) ; // Show the stage and its scene. myStage.show(); } } // JavaFX controls · // Keyboard Event handling ·
🌐
GitHub
raw.githubusercontent.com › mstr2 › jfx › cf1daa2e9516c9be6cb6fb6e196e09e6f503594b › modules › javafx.controls › src › main › java › com › sun › javafx › scene › control › behavior › TwoLevelFocusComboBehavior.java
https://raw.githubusercontent.com/mstr2/jfx/cf1daa...
import javafx.scene.Scene; import javafx.scene.input.KeyEvent; import javafx.beans.value.ChangeListener; import javafx.event.Event; import javafx.event.EventDispatcher; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; public class TwoLevelFocusComboBehavior extends TwoLevelFocusBehavior { public TwoLevelFocusComboBehavior(Node node) { tlNode = node; // listen to all keyevents, maybe tlNode.addEventHandler(KeyEvent.ANY, keyEventListener); tlNode.addEventHandler(MouseEvent.MOUSE_PRESSED, mouseEventListener); tlNode.focusedProperty().addListener(focusListener); // block Scr
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-8324232
Loading...
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.scene.input.KeyCode.isFunctionKey()" because the return value of "javafx.scene.input.KeyEvent.getCode()" is null at javafx.controls/com.sun.javafx.scene.control.behavior.TextInputControlBe...
🌐
Reddit
reddit.com › r/learnprogramming › [java][javafx] - using a key to run a method without focus?
r/learnprogramming on Reddit: [Java][JavaFX] - Using a key to run a method without focus?
December 26, 2014 -

I've picked up Java/JavaFX recently and it's going pretty well, I'm developing an application where a user enters a set of data into a set of textfields, then when they're done they press "Save", and that data is stored to a data table which is saved to an XML file to store it.

I've also written a Keyevent method where if the user presses "Enter", the data is saved without having to click the save button.

However, for this Keyevent to work the save button has to have the "focus" of the program. If the cursor is in a textfield and you press enter nothing happens. I have tried using the .requestFocus() method to give the button focus whenever enter is pressed and then save the data but this doesn't work. It doesn't give any errors either.

Any advice on how to give the button the program's focus or how to do this a different way?

🌐
Yakovfain
yakovfain.com › 2015 › 02 › 13 › javafx-8-the-keyboard-events-are-not-being-processed-if-a-scene-has-only-shapes
JavaFX 8: The keyboard events are not being processed if a scene has only shapes
February 13, 2015 - package sample; import javafx.fxml.FXML; import javafx.scene.Group; import javafx.scene.input.KeyEvent; public class Controller { @FXML Group theGroup; public void initialize(){ theGroup.setFocusTraversable(true); // doesn't have any effect theGroup.requestFocus(); // doesn't have any effect } public void keyHandler(KeyEvent event){ System.out.println(&quot;A Key was pressed&quot;); } }
Top answer
1 of 3
2
nvm, my keys already are smooth enough XD I am dumb, this is a dumb post, I facepalmed myself.
2 of 3
0
//here is my code · import javafx.animation.AnimationTimer; · import javafx.application.Application; · import javafx.event.EventHandler; · import javafx.scene.Group; · import javafx.scene.Scene; · import javafx.scene.input.KeyCode; · import javafx.scene.input.KeyEvent; · import javafx.scene.paint.Color; · import javafx.scene.shape.Rectangle; · import javafx.stage.Stage; · public class SmoothKeyEvents extends Application { · public final static String TITLE = "simple key-input program"; · public final static short WIDTH = 1280; · public final static short HEIGHT = 720; · private Stage window; · private Scene mainS; · private Group groupS; · private Rectangle rect; · private int x = 50; · private int y = 50; · private int velX = 0; · private int velY = 0; · @Override · public void start(Stage primaryStage) { · groupS = new Group(); · mainS = new Scene(groupS, WIDTH, HEIGHT, Color.DARKBLUE); · window = primaryStage; · window.setScene(mainS); · window.setTitle(TITLE); · window.show(); · window.requestFocus(); · rect = new Rectangle(); · rect.setFill(Color.MEDIUMSPRINGGREEN); · rect.setX(x); · rect.setY(y); · rect.setWidth(150); · rect.setHeight(150); · groupS.getChildren().add(rect); · mainS.setOnKeyPressed(new EventHandler(){ · @Override · public void handle(KeyEvent ke) { · if(ke.getCode() == KeyCode.A) { · setVelX(-9); · } · if(ke.getCode() == KeyCode.S) { · setVelY(9); · } · if(ke.getCode() == KeyCode.D) { · setVelX(9); · } · if(ke.getCode() == KeyCode.W) { · setVelY(-9); · } · } · }); · mainS.setOnKeyReleased(new EventHandler(){ · @Override · public void handle(KeyEvent ke) { · if(ke.getCode() == KeyCode.A) { · setVelX(0); · } · if(ke.getCode() == KeyCode.S) { · setVelY(0); · } · if(ke.getCode() == KeyCode.D) { · setVelX(0); · } · if(ke.getCode() == KeyCode.W) { · setVelY(0); · } · } · }); · final AnimationTimer at = new AnimationTimer() { · @Override · public void handle(long arg0) { · x += velX; · rect.setX(x); · y += velY; · rect.setY(y); · } · }; · at.start(); · } · public void setVelX(int velX) { · this.velX = velX; · } · public void setVelY(int velY) { · this.velY = velY; · } · public void stop() { · System.out.println("program exited"); · } · public static void main(String[] args) { · launch(args); · } · }
🌐
OpenJFX
openjfx.io › javadoc › 11 › javafx.graphics › javafx › scene › input › KeyCodeCombination.html
KeyCodeCombination (JavaFX 11)
Tests whether this key combination matches the key combination in the given KeyEvent. It uses only the key code and the state of the modifier keys from the KeyEvent in the test.