简体   繁体   中英

Charva : JTextArea : Test a char (KeyEvent) before print it?

I am coding a Point of sale software using Charva. I have a command line in a JTextArea. I want to allow only special character in it. I want to test the key press by the user before it will be printed. If it is an allowed character, it will be printed, if not, it will not be printed.

Another approach, is to erase the character if it is not allowed, but I was not able to do it for some reasons.

I would do something like this:

 private void myTextArea_KeyTyped(java.awt.event.KeyEvent evt) {                                    

    String key = String.valueOf(evt.getKeyChar());
    String validChars = "[a-zA-Z0-9]";

    if(!key.matches(validChars))
        evt.consume();
 }

Explanation: Take the input char, turn it into a string (dunno if char has .matches(regexp), chars in java are not my friends), check if matches with my regexp, if not, the event is consumed and the key is not printed.

PS: The event used here is KeyTyped .

PS2: If you're not familiarized with regular expressions (regexp), check this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM