add Action to JComponent - Java Swing

Java examples for Swing:JComponent

Description

add Action to JComponent

Demo Code


//package com.java2s;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

public class Main {
    public static void addAction(JComponent component, String keyStroke,
            AbstractAction action) {
        KeyStroke ks = KeyStroke.getKeyStroke(keyStroke);
        if (ks == null)
            throw new IllegalArgumentException("invalid key stroke: "
                    + keyStroke);//from   ww  w  .  j  a va 2 s  .  com
        Object key = ks + "-" + System.currentTimeMillis();
        component.getActionMap().put(key, action);
        component.getInputMap().put(ks, key);

    }
}

Related Tutorials