Search code examples
keycode

JavaFX determinate if key pressed between a and Z


I have a ListView<String> in JavaFX and would like to determinate if the user presses a key between a(lowercase) and Z(uppercase).

My code to handle it looks like this:

@FXML
private void chooseElementByKey(KeyEvent event){
    if(event.getCode() == KeyCode.TAB){
        textfieldElement.setText("Element 1");
        event.consume();
        textfieldElement.requestFocus();
    }else if(/*put magic here*/){
        //more magic ...
    }
}

So I want to determinate if a key between a and Z is pressed. There must be a better way then

if(event.getCode() == KeyCode.a || event.getCode() == KeyCode.b ... and so on

Thanks for your help!


Solution

  • Using the link in my comment:

    https://docs.oracle.com/javafx/2/api/javafx/scene/input/KeyCode.html

    KeyCode has isLetterKey() which:

    Returns true if this key code corresponds to a letter key

    So I believe you should also be able to do if(event.getKeyCode().isLetterKey()). However, it doesn't define what is considered "a letter key", so I'm not 100% sure this will work for you if you don't want to allow non-English characters for example.

    Edit: According to this link:

    https://bugs.openjdk.java.net/browse/JDK-8090108

    There are some bugs with isLetterKey()'s handling of non-English characters, ex:

    KeyCode.isLetterKey returns false for Swedish letters ö, ä and å.