You have few issues with your code :
You are using
onKeyTypedinstead ofonKeyPressed. For more information visit this linkYou are most probably using
java.awt.event.KeyEvent, which will not work withJavaFX events. Try to usejavafx.scene.input.KeyEvent.The reason I came to this conclusion is because JavaFX doesn't support
KeyEvent.VK_ENTERbut instead haveKeyCode.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 OverflowVideos
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?