Reputation: 167
I made a extremely simple program to understand the workings of KeyListener, but for some reason none of my methods are being called when any key is hit. I would really appreciate if someone could give me some input.
import java.applet.*;
import java.awt.event.*;
public class ClassOne extends Applet implements KeyListener {
public void init(){
this.addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent arg0) {
System.out.println("Pressed");
}
@Override
public void keyReleased(KeyEvent k) {
System.out.println("Released");
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
Upvotes: 1
Views: 134
Reputation: 347194
KeyListener
s are designed to provide key notifications to the component that they registered to only when the component is focusable AND has focus. That means that it won't respond to key events if some other component has focus (or your component isn't focusable).
A better solution would be to use the Key Bindings API, but this would require you to use a JApplet
, which the raises the question of, why are you using an Applet
anyway...?
Upvotes: 1