0
@FXML
private void login(Event event) throws IOException {
    String userName = emailId.getText().trim();
    String password = passwordId.getText().trim();

    try {
        if(isValidCredentials(userName, password)){
            System.out.println("Login Successfull");
            Parent mainScreen = FXMLLoader.load(getClass().getResource("MainPage.fxml"));
            Scene mainScene = new Scene(mainScreen);
            Stage mainStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
            mainStage.hide();
            mainStage.setScene(mainScene);
            mainStage.setTitle("Main Screen");
            mainStage.show();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

This login method is being called on mouse click of login button. What i want is same method to be called when enter key is pressed on login page.

SAJAL MATHUR
  • 67
  • 1
  • 2
  • 15
  • https://stackoverflow.com/questions/13880638/how-do-i-pick-up-the-enter-key-being-pressed-in-javafx2 – sagarr Sep 18 '17 at 16:40

1 Answers1

2

You can make the login button the default button: that way it will fire action events when the enter key is pressed:

<Button fx:id="loginButton" text="Login" onAction="#login" defaultButton="true" />

This will work unless a control that consumes an Enter key press has the keyboard focus, which is likely what you need. If you also have text fields, for example, and you want the login action to be performed when the enter key is pressed on those text fields, just set the onAction handler for the text fields as well:

<TextField fx:id="emailId" onAction="#login" />
James_D
  • 201,275
  • 16
  • 291
  • 322