My window is a java.awt.Frame, and inside of the Frame are two Panels (java.awt.Panel). I'm trying to make it so that the window handles buttons I press.
I tried using a KeyListener, making the Frame implement the KeyListener. I added the KeyListener to the Frame, but the KeyListener functions didn't do anything when I pressed keys. (I tried printing with System.out.println().)
I tried following this tutorial: http://tips4java.wordpress.com/2008/10/10/key-bindings/ . Here is the my attempt to handle pressing the SPACEBAR:
public void registerActions(){ //01
Action myAction = new AbstractAction(){ //02
@Override //03
public void actionPerformed(ActionEvent e) { //04
System.out.println("GREAT SUCCESS!"); //05
} //06
}; //07
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0); //08
component.getInputMap().put(key, "myAction"); //09
component.getActionMap().put("myAction", myAction); //10
} //11
The main problem is that I don't know what 'component' should be in lines 09 & 10, because my application does not have any JComponents.
Is there a way to do this without using swing components? Or is there another way to handle key presses?
I found that I could do this with an AWTEventListener.
public class MyFrame extends Frame implements AWTEventListener {
...
public MyFrame(String title){
super(title);
...
this.getToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
}
@Override
public void eventDispatched(AWTEvent event) {
if(event instanceof KeyEvent){
KeyEvent key = (KeyEvent)event;
if(key.getID()==KeyEvent.KEY_PRESSED){ //Handle key presses
System.out.println(key.getKeyChar());
//TODO: do something with the key press
key.consume();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With