views:

44

answers:

3

How can I know when the key typed change my text? Or if the key is a char?

+1  A: 

i guess you want to know wether typing a specific key actually prints a char or is some "invisible" control character or something:

in this case you can check the typed key in the KeyEvent which gets passed into the implemented methods of the KeyListener:

this quick example should work, although i didnt test it. It constructs a new String on the char returned by the KeyEvent, than invokes the length() method to chekc if the char created a readable character in the String. kinda hacky but i hope you get the gist of it

public void keyReleased(KeyEvent ke){
    if (new String(ke.getKeyChar()).length() == 0){
        // do something important...
    }
}

alternativley you can use ke.getKeyCode() and check vs the static fields in KeyEvent (VK_F12,VK_ENTER...)

check here:

http://download-llnw.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html

smeg4brains
It doesn't work! :(When I create the string after backspace, the value is "\b", what means length equals 1.
Victor
reading the javadoc yielded that getKeyCode()==KeyEvent.VK_UNDEFINED should work...
smeg4brains
+1  A: 

The interface KeyListener contain three methods:

void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)

So, if you get the char in the KeyEvent object like:

if ("a".equals(KeyEvent.getKeyChar()))
    System.out.println("It's a letter")
Agusti-N
A: 

How to Write a Document Listener

camickr