Install the keystrokes for several actions on a single button JComponent. - Java Swing

Java examples for Swing:Action

Description

Install the keystrokes for several actions on a single button JComponent.

Demo Code

/*// w ww.j av a 2  s .c  om
 *  Jajuk
 *  Copyright (C) The Jajuk Team
 *  http://jajuk.info
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *  
 */
//package com.java2s;

import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

public class Main {
    /**
     * Install the keystrokes for several actions on a single button. The
     * keystrokes are added with {@link JComponent#WHEN_IN_FOCUSED_WINDOW}
     * condition.
     * 
     * @param component The component to which the key stroke will be added.
     * @param actions The actions to add to the keystrokes.
     */
    public static void installKeystrokes(JComponent component,
            Action... actions) {
        for (Action action : actions) {
            KeyStroke stroke = (KeyStroke) action
                    .getValue(Action.ACCELERATOR_KEY);
            if (stroke != null) {
                InputMap keyMap = component
                        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                keyMap.put(stroke, action);
                ActionMap actionMap = component.getActionMap();
                actionMap.put(action, action);
            }
        }
    }
}

Related Tutorials