java – How to use KeyEvent in JavaFX project?
java – How to use KeyEvent in JavaFX project?
You have few issues with your code :
- You are using
onKeyTyped
instead ofonKeyPressed
. For more information visit this link - You 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 doesnt support
KeyEvent.VK_ENTER
but 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);
}
}