Search code examples
javaswingjtextfield

How to return keyCode of Character


I have following task to do.

I have char[] text. I want to check if character which was pressed in JTextField is equal to text[0] = 'a'; I need it to compare two characters even if these characters are spaces.

I have started like this ...

   public void keyPressed(KeyEvent e) {


       int charcode = e.getKeyCode();   


    }

Then I don't know how to get keyCode of character.


Solution

  • " I want to check if character which was pressed in JTextField"

    Don't use a KeyListener for a JTextField. Instead use a DocumentListener (which listen for changes in the underlying document of the text field) or a DocumentFilter (which will allow you to filter out "real-time" typed character). Without a better understanding of what you are trying to accomplish when a space entered is detected, I couldn't recommend which one will be more suitable. But you can go to How to Write DocumentListeners for more details.