Search code examples
javafxkeyevent

javafx 2.2 keycode.enter


I am working on an application in JavaFX 2.2. I am logging on to active directory with two fields (username and password) and have a log on button. It all works perfectly. However I have added a KeyEvent EventHandler to handle the key event of pressing ENTER which works. The problem is it also is used when the user presses the SHIFT Key. Below is the code for my Handler and there are no other KeyEvent Handlers being used in the application.

import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent; 
...   
private EventHandler<KeyEvent> keyListener = new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        if(event.getCode() == KeyCode.ENTER); {
            startLogin();
            getContext();
            try {
                checkUserLevel();
            } catch (Exception e) {
                actionTarget.setText("Unable to authenticate user\n" + userTextField.getText());
            }
            event.consume();
        } 
    }
};

Is this a bug in JavaFX?


Solution

  • You have to remove the semi-colon. From

    if(event.getCode() == KeyCode.ENTER); {
    

    To

    if(event.getCode() == KeyCode.ENTER) {
    

    Also, in Swing I know for sure you can add an ActionListener to a JTextBox directly, and it'll trigger the action event when enter is pressed while the JTextBox as focus. It'll prevent having your action being triggered in unrelated context. Hopefully something like that exist in JavaFX!