0

In my program, I have a Jbutton (named "Clear") that clears several textfields in GUI. I want to replace this button with Escape key such that pressing Escape key is same as pressing that button. (I don't want that Jbutton in my program)

user2723764
  • 25
  • 1
  • 2
  • 6
  • possible duplicate of [Swing: how do I close a dialog when the ESC key is pressed?](http://stackoverflow.com/questions/642925/swing-how-do-i-close-a-dialog-when-the-esc-key-is-pressed) – Maroun Sep 12 '13 at 06:40

3 Answers3

3

Basically, you want to start by using key bindings.

Now, me, personally, I would attach a binding to your "Clear" button so the use has two choices...for example...

JButton clear = new JButton("Clear");

InputMap im = clear .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = clear .getActionMap();

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "clear");
am.put("clear", new ClearFieldsAction());
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

If you want to remove the button and listen to key events for the hole application, you can create a

EventQueue

and register this EventQueue at

Toolkit.getDefaultToolkit().getSystemEventQueue().push(INSTANCE_EVENT_QUEUE);

The method

protected void dispatchEvent(AWTEvent e)

will get the AWTEvent which you can handle. Like:

@Override
protected void dispatchEvent(AWTEvent e) {
    // handle event and/or
    super.dispatchEvent(e);
}

Key Event you handle like

    private void handleAWTEvent(AWTEvent event) {

    if (event instanceof KeyEvent) {
        KeyEvent keyEvent = (KeyEvent)event;

        if (keyEvent.getID() != KeyEvent.KEY_PRESSED) {
            return;
        }

        if (keyEvent.isAltDown() ^ keyEvent.isControlDown() && !keyEvent.isShiftDown()) {
   ...
Markus Lausberg
  • 12,177
  • 6
  • 40
  • 66
0

try this, it works for me

InputMap im = clear.getRootPane().getInputMap(...
ActionMap am = clear.getRootPane().getActionMap(...
David Buck
  • 3,752
  • 35
  • 31
  • 35
Ico
  • 1
  • 1