0

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

Victor
  • 8,309
  • 14
  • 80
  • 129
  • 1
    What text? Is it in a text field, text area, etc? How are you listening? Do you only care if the key pressed is in a text area, or only if it isn't? A little more about what you are trying to accomplish from listening for the key press would help as well. – aperkins Jul 28 '10 at 17:21

3 Answers3

2

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
  • 3,956
  • 10
  • 40
  • 47
1

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://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
fasseg
  • 17,504
  • 8
  • 62
  • 73
  • It doesn't work! :( When I create the string after backspace, the value is "\b", what means length equals 1. – Victor Jul 28 '10 at 17:40
  • reading the javadoc yielded that getKeyCode()==KeyEvent.VK_UNDEFINED should work... – fasseg Jul 28 '10 at 18:05
1

You need a document listener. See the oracle docs for more information: How to Write a Document Listener

BetaRide
  • 16,207
  • 29
  • 99
  • 177
camickr
  • 321,443
  • 19
  • 166
  • 288