Reputation: 1
I currently have my program display whatever key is pressed, ranging from letters to numbers and symbols. The problem is, I only want it to display the letters, and say "not valid" for everything else.
Here is what I have now:
public void keyPressed(KeyEvent e) {
String keyCode = KeyEvent.getKeyText(e.getKeyCode());
statusMsg.setText("You selected " + keyCode);
}
Edit: Thank you everyone for the help!
Upvotes: 0
Views: 968
Reputation: 1680
I think this is the simplest way:
private void formKeyPressed(java.awt.event.KeyEvent evt) {
String keyCode = KeyEvent.getKeyText(evt.getKeyCode());
if (keyCode.length()==1 && Character.isLetter(keyCode.charAt(0))) {
statusMsg.setText("You selected " + keyCode);
} else {
statusMsg.setText("Not valid");
}
}
First it checks if the string's size is 1, because if it is bigger it means that the key is something like "Enter". Then, it uses the isLetter
function of the Character class to check if the first char of the keyCode
is a letter and not a number.
Upvotes: 2
Reputation: 86
You may want to use e.getKeyChar()
instead which will give you the char representing A if the user types in shift + a
for example. That said, you have a couple options:
Matcher matcher = Pattern.compile("[a-zA-Z]").matcher()
. Then you can check matcher.matches(keyCode)
(e.g. keyCode = matcher.matches(keyCode) ? keyCode : "Not Valid"
on the third line of your method)You could just use the getKeyChar method above and check the int value is between 'a' and 'Z'. This would look like:
char keyChar = e.getKeyChar(); String message = ((keyChar >= 'A' && keyChar <= 'Z') || (keyChar >= 'a' && keyChar <= 'z' ) ? "You selected " + keyChar : "Not Valid"
You can use the Character.isLetter()
method
Upvotes: 3
Reputation: 4596
ASCII codes...
int code = Integer.paseInt(keyCode);
if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z')){
//code represents a letter key pressed
} else {
//code does not represent a letter key pressed
}
Characters are understood as integers in the above code (e.g. A
is 65).
Upvotes: 1
Reputation: 30839
Looking at JavaDoc for KeyEvent
class (here), it seems it has all the key codes defined as constants, e.g:
public static final int VK_A
VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
So, you need to get the key code and make sure it's between VK_A
and VK_Z
. If not, you can show the error message.
Upvotes: 2