Java JButton addEnterListener(JComponent c, final JButton b)

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

Description

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

License

Open Source License

Parameter

Parameter Description
b the Ok button(or Next or Done)
c the focused Jcomponent

Declaration

public static void addEnterListener(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   www .ja  v  a2s  .c o m*/
     * This method implements hotkey  binding for [Enter] for currently focused JComponent with a "Ok" Button.
     * Pressing Enter, would mimic as clicking on Ok button.
     * 
     * @param b
     *       the Ok button(or Next or Done)
     * @param c
     *       the focused Jcomponent
     * @author Mukarram Tailor
     */
    public static void addEnterListener(JComponent c, final JButton b) {
        c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "pressOK");
        c.getActionMap().put("pressOK", new AbstractAction() {

            private static final long serialVersionUID = 1L;

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

Related

  1. addActionToButton(JButton button, final Runnable action)
  2. addCRListener(JComponent c, final JButton b)
  3. adjustButtonMargins(Insets margin, JButton... buttons)
  4. adjustButtonWidth(JButton button, int minWidth, int minHeight)
  5. btnHover(JButton btn)
  6. buttonState(JButton button, boolean boolArrayOfErrors[])