rockZ
rockZ

Reputation: 875

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!

Upvotes: 0

Views: 2132

Answers (2)

GreenAtomic
GreenAtomic

Reputation: 96

Although the question has already been answered, I'm going to make another contribution for those, who can't use the isLetterKey() method.

A - Z

For those who just don't want (or even can't) use the isLetterKey() function, this would be a good way to solve it:

if(ke.getKeyCode() >= KeyEvent.VK_A && ke.getKeyCode() <= KeyEvent.VK_Z) {
    //do Something
}

With Special Chars

For those who cannot access the isLetterKey() function due to special chars in their language, there is also the following possibility:

1. Create a char array, containing all special chars

char[] specialChars = {'ä', 'ö', 'ü'};
boolean foundSpecialChar = false;

2. Compare the content of your array with the KeyCode()

for(int i = 0; i < specialChars.length; i++) {
    if(ke.getKeyChar() == specialChars[i]) {
        foundSpecialChar = true;
    }
}

3. add an additional check to the if condition of the A - Z example

if((ke.getKeyCode() >= KeyEvent.VK_A && ke.getKeyCode() <= KeyEvent.VK_Z) || foundSpecialChar) {
//do Something here
}

Upvotes: 1

sab669
sab669

Reputation: 4104

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 å.

Upvotes: 1

Related Questions