Issue
sorry for the questions... but I'm a little stuck again.
I ask these questions so I can get the most out of my time/learning.
I am trying to fire a click event (so when i manually click the login btn) with the enter key.
code
usernameField.setOnKeyPressed((KeyEvent event) -> {
if(event.getCode()==KeyCode.ENTER){
loginBtn.fire();
System.out.println("Worked");
}
});
That does what it's supposed to, almost. the system out message appears but does now fire the loginBtn.
I am using JavaFX and JFXButtons/textboxes if that makes a difference
Solution
Text fields fire action events when the user presses the enter key. So all you need is
EventHandler<ActionEvent> loginHandler = e -> {
// handle login here...
};
usernameTextField.setOnAction(loginHandler);
loginBtn.setOnAction(loginHandler);
Or, if you prefer;
usernameTextField.setOnAction(e -> handleLogin());
loginBtn.setOnAction(e -> handleLogin());
// ...
private void handleLogin() {
// handle login here...
}
If you are using FXML, you can just map both onAction
handlers to the same controller method:
<TextField fx:id="usernameTextField" onAction="#login" />
<Button fx:id="loginBtn" text="Log In" onAction="#login" />
and then in the controller
public class Controller {
// ...
@FXML
private void login() {
// login action here..
}
// ...
}
Answered By - James_D
Answer Checked By - Marilyn (JavaFixing Volunteer)