Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyListener, keyPressed versus keyTyped

I have a JFrame (well, a class which extends JFrame) and I want to do an action when I press the F5 key. So, I made the class implement KeyListener. And with that, came three methods, keyPressed, keyReleased, and keyTyped.

Which of these methods should I use to listen for F5 being pressed? keyPressed or keyTyped? I currently have the following, however it does not print anything when I press F5.

public void keyPressed(KeyEvent e) {     if(e.getKeyCode() == KeyEvent.VK_F5)         System.out.println("F5 pressed"); }  public void keyReleased(KeyEvent arg0) {     // TODO Auto-generated method stub  }  public void keyTyped(KeyEvent arg0) {     // TODO Auto-generated method stub  } 
like image 856
CodeGuy Avatar asked Aug 15 '11 22:08

CodeGuy


People also ask

What is the difference between keyTyped and keyPressed?

keyPressed is fired whenever any key press occurs. keyTyped is fired when a key is pressed that can be converted into a unicode character.


2 Answers

keyPressed - when the key goes down keyReleased - when the key comes up keyTyped - when the unicode character represented by this key is sent by the keyboard to system input. 

I personally would use keyReleased for this. It will fire only when they lift their finger up.

Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.

like image 122
corsiKa Avatar answered Oct 04 '22 09:10

corsiKa


Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

like image 23
camickr Avatar answered Oct 04 '22 09:10

camickr