0
\$\begingroup\$

I have a basic text field setup in LWJGL, however pressing any modifier keys (Shift, F1-19, Page Up, etc.) inputs a space into the text field. How would I ignore those characters? Here's some code so far.

Note: value is a string variable

while (Keyboard.next()) {
    if (Keyboard.getEventKeyState()) {
        if (Keyboard.getEventKey() == Keyboard.KEY_BACK) { //Backspace
            if (value.length() > 0) {
                value = value.substring(0, value.length() - 1);
            }
        } else if (/* Character is not a modifier key*/) {
            value += Keyboard.getEventCharacter();
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ Did you tried the if (Keyboard.event != Keyboard.LEFT_SHIFT, ...)? \$\endgroup\$ – Bálint Feb 8 '16 at 7:03
  • \$\begingroup\$ @Bálint I tried that. Its really tedious, and it doesn't seem to work pbs.twimg.com/media/CaouSL4UYAEKoRb.png \$\endgroup\$ – CraftedCart Feb 8 '16 at 16:39
1
\$\begingroup\$

You need to check for Character.isLetterOrDigit(char), and if it returns false, skip it.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ What about punctuation...? \$\endgroup\$ – CraftedCart Feb 8 '16 at 18:19
  • \$\begingroup\$ "||" os a great thing \$\endgroup\$ – Bálint Feb 8 '16 at 18:22
0
\$\begingroup\$

Add this where you add the code to the string:

value += String.valueOf(Keyboard.getEventCharacter()); 
value = value .replaceAll("[^\\w\\s\\]","");
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Welp, seems a bunch of RegEx works...

if (Pattern.matches("[A-Za-z0-9\\s_\\+\\-\\.,!@#\\$%\\^&\\*\\(\\);\\\\/\\|<>\"'\\[\\]\\?=]", String.valueOf(Keyboard.getEventCharacter()))) {
    value += Keyboard.getEventCharacter();
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.