0

Im trying to get my KeyEvent working. Sadly the keyTyped(KeyEvent e) isnt responding at all. :)

I implemented the KeyEvnet to my class.

I assigned the listener like following:

JTextfield searchBar = new JTextField();
searchBar.addKeyListener( this );

My key event looks like this:

@Override
public void keyTyped(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
        System.out.println("pressed");
        try {
            int browser = getSelectBrowser().getSelectedIndex();
            logic.search( searchBar.getText(), searchInfo, browser, isURL );
        } catch (InterruptedException ie) {
            System.out.println( "Pressed fail" );
        }
        this.repaint();
    }
}

I also tried the Listener in a second test Gui and were it also does not work.

:-)

SunflowerToadTheOrbiter
  • 1,285
  • 4
  • 15
  • 25
  • 1
    "*Does not work*" is not an acceptable problem description. http://stackoverflow.com/help/how-to-ask –  Apr 04 '16 at 13:09
  • Have you tried putting a `System.out.println(...)` outside your `if`? – Tiz Apr 04 '16 at 13:12
  • @Tiz System.out.println(...) is just to check if it actually went through the listener ;) It should work with a println(). – SunflowerToadTheOrbiter Apr 04 '16 at 13:15
  • @itknocks Yeah, I know. My point was that you won't see the print out **unless enter is pressed**. Putting the `println` outside the `if` will tell you if the method is called for other keys. – Tiz Apr 04 '16 at 13:36
  • @Tiz oh sorry i miss understood your answer. when I put it outside of the 'if' ieverything I press prints me a 0 – SunflowerToadTheOrbiter Apr 04 '16 at 13:39
  • @itknocks are you specifically trying to use the enter key, or are you looking to handle all key presses? – Tiz Apr 04 '16 at 13:47

2 Answers2

0

use "keyPressed" instead of "keyTyped". keyTyped listens only on alphanumeric chars

SunflowerToadTheOrbiter
  • 1,285
  • 4
  • 15
  • 25
licklake
  • 236
  • 4
  • 15
0

You wont see this listener called when you press enter, so your println will never be called. Pressing enter on a JTextField will call the attached ActionListener, if there is one.

To get this working, add an ActionListener to the text field and put the code you want to run when enter is pressed in there.

You can read more about it here. Thanks to tak3shi for linking that in the comments.

Community
  • 1
  • 1
Tiz
  • 680
  • 5
  • 17