Java Utililty Methods Swing KeyStroke

List of utility methods to do Swing KeyStroke

Description

The list of methods to do Swing KeyStroke are organized into topic(s).

Method

voidsetKeyBinding(String actionKey, int key, int modifiers, AbstractAction action, JComponent component)
set Key Binding
ActionMap actionMap = component.getActionMap();
InputMap inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
KeyStroke keyStroke = KeyStroke.getKeyStroke(key, modifiers);
inputMap.put(keyStroke, actionKey);
actionMap.put(actionKey, action);
voidsetKeyStroke(JComponent component, KeyStroke keyStroke, Action action)
set Key Stroke
InputMap inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
if (inputMap != null) {
    ActionMap actionMap = component.getActionMap();
    inputMap.put(keyStroke, KEYID);
    if (actionMap != null) {
        actionMap.put(KEYID, action);
voidsetUpCycle(JComponent comp, int key)
Set the up-cycle key for a particular component As they said in the book (pg 1108), due to a note you have to press the key twice.
Set upKeys = comp.getFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);
Set newUpKeys = new HashSet(upKeys);
newUpKeys.add(AWTKeyStroke.getAWTKeyStroke(key, 0));
comp.setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, newUpKeys);
KeyStrokestringToKeyStroke(String s)
string To Key Stroke
throw new IllegalAccessError("Work in progress");
StringstrokeToPrefs(KeyStroke prefsStroke)
Converts a KeyStroke into a string representation for preference storage.
if (prefsStroke == null)
    return null;
else
    return String.valueOf(prefsStroke.getModifiers()) + ' ' + String.valueOf(prefsStroke.getKeyCode());
voidsynchronizeKeyboardActions(JComponent sourceComponent, JComponent targetComponent, KeyStroke[] keyStrokes, int condition)
synchronize Keyboard Actions
for (KeyStroke keyStroke : keyStrokes) {
    ActionListener actionListener = sourceComponent.getActionForKeyStroke(keyStroke);
    if (actionListener != null)
        targetComponent.registerKeyboardAction(actionListener, keyStroke, condition);
voidsynchronizeKeyboardActions(JComponent sourceComponent, JComponent targetComponent, KeyStroke[] keyStrokes, int condition)
Registers all actions registered on the source component and registered them on the target component at the specified condition.
for (KeyStroke keyStroke : keyStrokes) {
    ActionListener actionListener = sourceComponent.getActionForKeyStroke(keyStroke);
    if (actionListener != null) {
        targetComponent.registerKeyboardAction(actionListener, keyStroke, condition);
voidunregisterKeyBoardAction(JComponent comp, Action action)
unregister Key Board Action
unregisterKeyBoardAction(comp, action, JComponent.WHEN_IN_FOCUSED_WINDOW);
MwithKeyStroke(M jmi, KeyStroke ks)
with Key Stroke
jmi.setAccelerator(ks);
return jmi;