Java JButton Escape addEscListener(JComponent c, final JButton b)

Here you can find the source of addEscListener(JComponent c, final JButton b)

Description

This method implements hotkey binding for [Esc] for currently focused JComponent with a "Cancel" Button.

License

Open Source License

Parameter

Parameter Description
b the cancel button(or exit or Back)
c the focused JComponent

Declaration

public static void addEscListener(JComponent c, final JButton b) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

public class Main {
    /**//from   ww w  .  java  2  s  .co m
     * This method implements hotkey  binding for [Esc] for currently focused JComponent with a "Cancel" Button.
     * Pressing Esc, would mimic as clicking on cancel button.
     * 
     * @param b
     *       the cancel button(or exit or Back)
     * @param c
     *       the focused JComponent
     * @author Mukarram Tailor
     */
    public static void addEscListener(JComponent c, final JButton b) {
        c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "pressCancel");
        c.getActionMap().put("pressCancel", new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent cancel) {
                b.doClick();
            }
        });
    }
}

Related

  1. addEscListener(JComponent c, final JButton b)
  2. fillRow(int row, String labelDesc, JComponent[] boxes, JButton button, Container panel)