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
}
This question is related to
java
swing
jframe
key-bindings
keylistener
You should use keyPressed
if you want an immediate effect, and keyReleased
if you want the effect after you release the key. You cannot use keyTyped
because F5 is not a character. keyTyped
is activated only when an character is pressed.
private String message;
private ScreenManager s;
//Here is an example of code to add the keyListener() as suggested; modify
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_F5)
message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}
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.
Source: Stackoverflow.com