1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.xnap.commons.gui.shortcut;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import javax.swing.Action;
26 import javax.swing.JComponent;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 /***
31 * Manages Shortcut objects.
32 */
33 public class ShortcutManager
34 {
35
36 private static Log logger = LogFactory.getLog(ShortcutManager.class);
37
38 private static ShortcutManager instance = new ShortcutManager();
39 /***
40 * The list of unique shortcut objects.
41 */
42 private ArrayList<Shortcut> shortcuts = new ArrayList<Shortcut>();
43
44 private HashMap<String, ActionShortcut> shortcutsByCommandKey =
45 new HashMap<String, ActionShortcut>();
46
47 private ShortcutManager()
48 {
49 }
50
51 /***
52 * Returns the instance of <code>ShortcutManager</code>.
53 */
54 public static ShortcutManager getInstance()
55 {
56 return instance;
57 }
58
59 /***
60 * Adds a shortcut.
61 */
62 public synchronized void add(Shortcut shortcut)
63 {
64 shortcuts.add(shortcut);
65 }
66
67 /***
68 * Creates a new ActionShortcut for the action if there isn't already one
69 * and returns it.
70 * <br>
71 * <p>Only one action shortcut object can exist for the same preferences
72 * key. Additional components are all managed by the same action shortcut
73 * object.</p>
74 *
75 * @param action the action which should be performed when the shortcut is
76 * typed in the respective component
77 * @param c the component for which the shortcut and the action are
78 * registered
79 */
80 public synchronized ActionShortcut add(Action action, JComponent c)
81
82 {
83 String key = (String)action.getValue(Action.ACTION_COMMAND_KEY);
84 if (shortcutsByCommandKey.containsKey(key)) {
85 ActionShortcut a = shortcutsByCommandKey.get(key);
86 a.addComponent(c, action);
87 return a;
88 }
89 else {
90 ActionShortcut a = new ActionShortcut(action, c);
91 shortcuts.add(a);
92 shortcutsByCommandKey.put(key, a);
93 return a;
94 }
95 }
96
97 /***
98 * Returns the array of currently registered shorcuts.
99 */
100 public synchronized Shortcut[] getShortcuts()
101 {
102 return shortcuts.toArray(new Shortcut[0]);
103 }
104
105 /***
106 * Removes a currently registered shortcut.
107 */
108 public synchronized void remove(Shortcut shortcut)
109 {
110 shortcuts.remove(shortcut);
111 }
112
113 /***
114 * Removes a component from a currently registered action shortcut.
115 *
116 * <p>If the action shortcut's component count {@link
117 * ActionShortcut#getNumberOfComponents()} drops to 0, it is removed from
118 * the shortcut manager.</p>
119 */
120 public synchronized void remove(ActionShortcut shortcut, JComponent c)
121 {
122 shortcut.removeComponent(c);
123 if (shortcut.getNumberOfComponents() == 0) {
124 String key = (String)shortcut.getAction().getValue(Action.ACTION_COMMAND_KEY);
125 shortcutsByCommandKey.remove(key);
126 remove(shortcut);
127 }
128 }
129
130 }