Java Swing Key Action setKeyEvent(JComponent widget, int keyEvent, Runnable action)

Here you can find the source of setKeyEvent(JComponent widget, int keyEvent, Runnable action)

Description

set Key Event

License

Open Source License

Declaration

public static void setKeyEvent(JComponent widget, int keyEvent, Runnable action) 

Method Source Code


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

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Main {
    public static void setKeyEvent(JComponent widget, int keyEvent, Runnable action) {
        String inputMapKey = "key_" + keyEvent;
        widget.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyEvent, 0), inputMapKey);
        widget.getActionMap().put(inputMapKey, new AbstractAction() {
            @Override/*from  ww  w .j a  v a 2s  .  c om*/
            public void actionPerformed(final ActionEvent e) {
                action.run();
            }
        });
    }
}

Related

  1. replaceAction(InputMap map, char c)
  2. sendKeys(JComponent component, int modifiers, int key)
  3. setActionID(final Action a, final String id)
  4. setDefaultOkCancelKeyStrokes(final JRootPane rootPane, final Action okAction, final Action cancelAction)
  5. setEscapeKeyboardAction(final Window window, JComponent pane)
  6. setMnemonic(Action action)
  7. setTabFocusTraversalKeys(final JComponent component)
  8. setupAction(Action action, ResourceBundle bundle, String actionId)
  9. setUseStandardFocusTraversalKeys(Component comp, boolean use)