Reputation: 745
I don't get how do implement Keyboard actions at all.
Mouse clicks, Buttons, Textfield, Textarea I get just fine, Keyboard is like the Chinese wall to me.
I have something like this, and I'd like to implement the Keyboard to close when I press "C":
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestGUI
{
private KeyboardListener anEventListener;
public TestGUI()
{
initGUI();
}
private void initGUI()
{
//Prepare Frame
JFrame myFrame = new JFrame();
myFrame.setTitle("Test");
myFrame.setSize(550, 500);
myFrame.setLocation(600, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLayout(null);
KeyboardListener anEventListener = new KeyboardListener();
//Show Frame
myFrame.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TestGUI();
}
});
}
class KeyboardListener implements KeyListener
{
public void keyPressed (KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.VK_C)
{
System.exit(0);
}
}
public void keyReleased(KeyEvent event)
{
}
public void keyTyped (KeyEvent event)
{
}
}
}
Upvotes: 0
Views: 695
Reputation: 39217
Just add the line
myFrame.addKeyListener(anEventListener);
to register your listener within your frame and it will work fine.
Note: This will only handle the key events associated with your frame. If you have other components around you might want to handle it differently (see also how to use key bindings).
In your case you can build a version with key bindings quite easily:
JComponent rootPane = myFrame.getRootPane();
rootPane.getInputMap().put(KeyStroke.getKeyStroke("C"), "closeThisOne");
rootPane.getActionMap().put("closeThisOne", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Upvotes: 1
Reputation: 324207
and I'd like to implement the Keyboard to close when I press "C":
Then you should create a custom Action and use a JMenu with a close menu item and an accelerator.
The ExitAction
from Closing an Application will do this for you.
Upvotes: 3
Reputation: 6526
I would start by checking out Key Bindings. This is more reliable than KeyListeners
as it doesn't have many focus issues. Also, KeyListeners
is an old AWT solution for problems like this.
Upvotes: 3
Reputation: 12776
You haven't attached your KeyboardListener
to a component. You also aren't using the anEventListener
field defined in your class -- it's being shadowed inside initGUI
.
Upvotes: 1