Binds an ActionListener to both double-click and the enter key in the given JComponent. - Java Swing

Java examples for Swing:JComponent

Description

Binds an ActionListener to both double-click and the enter key in the given JComponent.

Demo Code


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;

public class Main{
    /**/*from  w w w  .ja v  a 2 s.  co m*/
     * Binds an ActionListener to both double-click and the enter key in the given component.
     */
    public static void bindDoubleClickAndEnter(final JComponent component,
            final ActionListener listener) {
        component.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    listener.actionPerformed(new ActionEvent(component,
                            ActionEvent.ACTION_PERFORMED, null,
                            e.getWhen(), e.getModifiers()));
                }
            }
        });
        // The most likely caller hands us an anonymous AbstractAction, so make sure 'action' has a name.
        final Action trampoline = new AbstractAction(
                "e.util.ComponentUtilities.setJListAction") {
            public void actionPerformed(ActionEvent e) {
                listener.actionPerformed(e);
            }
        };
        ComponentUtilities.initKeyBinding(component,
                KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), trampoline);
    }
    /**
     * Binds an Action to a JComponent via the Action's configured ACCELERATOR_KEY.
     */
    public static void initKeyBinding(JComponent component, Action action) {
        KeyStroke keyStroke = (KeyStroke) action
                .getValue(Action.ACCELERATOR_KEY);
        initKeyBinding(component, keyStroke, action);
    }
    /**
     * Binds an Action to a JComponent via the given KeyStroke.
     */
    public static void initKeyBinding(JComponent component,
            KeyStroke keyStroke, Action action) {
        String name = (String) action.getValue(Action.NAME);
        component.getActionMap().put(name, action);
        component.getInputMap().put(keyStroke, name);
    }
}

Related Tutorials