KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > editors > KeyStrokeEditor


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.form.editors;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.beans.PropertyEditorSupport JavaDoc;
25 import java.lang.reflect.*;
26 import java.util.*;
27 import javax.swing.*;
28
29 import org.netbeans.modules.form.NamedPropertyEditor;
30
31 import org.openide.awt.Mnemonics;
32 import org.openide.explorer.propertysheet.editors.XMLPropertyEditor;
33 import org.openide.util.NbBundle;
34
35 public class KeyStrokeEditor extends PropertyEditorSupport JavaDoc
36         implements XMLPropertyEditor, NamedPropertyEditor {
37     private String JavaDoc TXT_CTRL;
38     private String JavaDoc TXT_ALT;
39     private String JavaDoc TXT_SHIFT;
40
41     public KeyStrokeEditor() {
42         ResourceBundle bundle =
43             org.openide.util.NbBundle.getBundle(KeyStrokeEditor.class);
44         TXT_CTRL = bundle.getString("CTL_CtrlAsText"); // NOI18N
45
TXT_SHIFT = bundle.getString("CTL_ShiftAsText"); // NOI18N
46
TXT_ALT = bundle.getString("CTL_AltAsText"); // NOI18N
47
}
48
49     public String JavaDoc getJavaInitializationString() {
50         KeyStroke key =(KeyStroke) getValue();
51         int mods = key.getModifiers();
52         StringBuffer JavaDoc modsText = new StringBuffer JavaDoc();
53
54         if (0 !=(mods
55                  &(InputEvent.ALT_MASK | InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK))) {
56             if (0 !=(mods & InputEvent.ALT_MASK))
57                 modsText.append("java.awt.event.InputEvent.ALT_MASK"); // NOI18N
58
if (0 !=(mods & InputEvent.SHIFT_MASK)) {
59                 if (modsText.length() > 0)
60                     modsText.append(" | "); // NOI18N
61
modsText.append("java.awt.event.InputEvent.SHIFT_MASK"); // NOI18N
62
}
63             if (0 !=(mods & InputEvent.CTRL_MASK)) {
64                 if (modsText.length() > 0)
65                     modsText.append(" | "); // NOI18N
66
modsText.append("java.awt.event.InputEvent.CTRL_MASK"); // NOI18N
67
}
68         }
69         else
70             modsText.append("0"); // NOI18N
71

72         return "javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent." // NOI18N
73
+ getVirtualkeyName(key.getKeyCode()) + ", " + modsText.toString() + ")"; // NOI18N
74
}
75
76     public String JavaDoc getAsText() {
77         KeyStroke key = (KeyStroke) getValue();
78         return key != null ? keyStrokeAsString(key, true) : "null"; // NOI18N
79
}
80
81     public void setAsText(String JavaDoc text) throws IllegalArgumentException JavaDoc {
82         if (text == null || "".equals(text) || "null".equals(text)) { // NOI18N
83
setValue(null);
84             return;
85         }
86
87         KeyStroke key = keyStrokeFromString(text, true);
88         if (key == null)
89             throw new IllegalArgumentException JavaDoc("Unrecognized key: " + text); // NOI18N
90
else
91             setValue(key);
92     }
93
94     private static String JavaDoc getVirtualkeyName(int keycode) {
95         Field[] fields = KeyEvent.class.getDeclaredFields();
96         for (int i = 0; i < fields.length; i++) {
97             Field f = fields[i];
98             int modifiers = f.getModifiers();
99             if (Modifier.isPublic(modifiers)
100                 && Modifier.isStatic(modifiers)
101                 && Modifier.isFinal(modifiers)
102                 && f.getType() == Integer.TYPE
103                 && f.getName().startsWith("VK_")) { // NOI18N
104
try {
105                     if (f.getInt(KeyEvent.class) == keycode) {
106                         return f.getName();
107                     }
108                 }
109                 catch (IllegalAccessException JavaDoc ex) {
110                     ex.printStackTrace(); // should not happen
111
}
112             }
113         }
114         return null;
115     }
116
117     private KeyStroke keyStrokeFromString(String JavaDoc s, boolean i18ned) {
118         StringTokenizer st = new StringTokenizer(s, "+"); // NOI18N
119
String JavaDoc token;
120         int mods = 0;
121         int keycode = 0;
122
123         String JavaDoc alt = i18ned ? TXT_ALT : "Alt"; // NOI18N
124
String JavaDoc shift = i18ned ? TXT_SHIFT : "Shift"; // NOI18N
125
String JavaDoc ctrl = i18ned ? TXT_CTRL : "Ctrl"; // NOI18N
126

127         while (st.hasMoreTokens() &&(token = st.nextToken()) != null) {
128             if (alt.equalsIgnoreCase(token))
129                 mods |= InputEvent.ALT_MASK;
130             else if (shift.equalsIgnoreCase(token))
131                 mods |= InputEvent.SHIFT_MASK;
132             else if (ctrl.equalsIgnoreCase(token))
133                 mods |= InputEvent.CTRL_MASK;
134             else {
135                 String JavaDoc keycodeName = "VK_" + token.toUpperCase(); // NOI18N
136
try {
137                     keycode = KeyEvent.class.getField(keycodeName).getInt(KeyEvent.class);
138                 }
139                 catch (Exception JavaDoc e) {
140                     // ignore
141
}
142             }
143         }
144         if (keycode != 0)
145             return KeyStroke.getKeyStroke(keycode, mods);
146         else
147             return null;
148     }
149
150     private String JavaDoc keyStrokeAsString(KeyStroke key, boolean i18ned) {
151         String JavaDoc alt = i18ned ? TXT_ALT : "Alt"; // NOI18N
152
String JavaDoc shift = i18ned ? TXT_SHIFT : "Shift"; // NOI18N
153
String JavaDoc ctrl = i18ned ? TXT_CTRL : "Ctrl"; // NOI18N
154

155         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
156         int mods = key.getModifiers();
157         int modMasks[] = { InputEvent.SHIFT_MASK, InputEvent.CTRL_MASK,
158                            InputEvent.ALT_MASK, };
159         String JavaDoc modMaskStrings[] = { shift, ctrl, alt, };
160
161         for (int i = 0; i < modMasks.length; i++) {
162             if ((mods & modMasks[i]) != 0) {
163                 buf.append(modMaskStrings[i]);
164                 buf.append("+"); // NOI18N
165
}
166         }
167         String JavaDoc keyName = getVirtualkeyName(key.getKeyCode());
168         if (keyName != null) {
169             buf.append(keyName.substring(3));
170         }
171         return buf.toString();
172     }
173
174     //
175
// XMLPropertyEditor
176
//
177

178     public static final String JavaDoc XML_KEYSTROKE = "KeyStroke"; // NOI18N
179
public static final String JavaDoc ATTR_KEY = "key"; // NOI18N
180

181     public void readFromXML(org.w3c.dom.Node JavaDoc element) throws java.io.IOException JavaDoc {
182         if (!XML_KEYSTROKE.equals(element.getNodeName())) {
183             throw new java.io.IOException JavaDoc();
184         }
185         org.w3c.dom.NamedNodeMap JavaDoc attributes = element.getAttributes();
186         try {
187             String JavaDoc value = attributes.getNamedItem(ATTR_KEY).getNodeValue();
188             KeyStroke key = keyStrokeFromString(value, false);
189             if (key == null)
190                 throw new IllegalArgumentException JavaDoc();
191             else
192                 setValue(key);
193         }
194         catch (Exception JavaDoc e) {
195             throw new java.io.IOException JavaDoc();
196         }
197     }
198
199     public org.w3c.dom.Node JavaDoc storeToXML(org.w3c.dom.Document JavaDoc doc) {
200         KeyStroke key = (KeyStroke) getValue();
201         String JavaDoc str = key != null ? keyStrokeAsString(key, false) : "null"; // NOI18N
202

203         org.w3c.dom.Element JavaDoc el = doc.createElement(XML_KEYSTROKE);
204         el.setAttribute(ATTR_KEY, str);
205         return el;
206     }
207
208     //
209
// custom editor
210
//
211

212     public boolean supportsCustomEditor() {
213         return true;
214     }
215
216     public java.awt.Component JavaDoc getCustomEditor() {
217         return new CustomEditor();
218     }
219     
220     // NamedPropertyEditor implementation
221
public String JavaDoc getDisplayName() {
222         return NbBundle.getBundle(getClass()).getString("CTL_KeyStrokeEditor_DisplayName"); // NOI18N
223
}
224
225     private static String JavaDoc[] _virtualKeys;
226
227     private class CustomEditor extends JPanel
228     {
229         private KeyGrabberField _keyGrabber;
230         private JCheckBox _ctrl, _alt, _shift;
231         private JComboBox _virtualKey;
232
233         CustomEditor() {
234             setLayout(new GridBagLayout());
235             
236             ResourceBundle bundle =
237                 org.openide.util.NbBundle.getBundle(KeyStrokeEditor.class);
238
239             JLabel virtualKeyLabel = new JLabel();
240             Mnemonics.setLocalizedText(virtualKeyLabel, bundle.getString("CTL_VirtualKey")); // NOI18N
241

242             GridBagConstraints gbc = new GridBagConstraints();
243             gbc.gridx = 0;
244             gbc.gridy = 0;
245             gbc.gridwidth = 1;
246             gbc.anchor = gbc.WEST;
247             gbc.fill = gbc.NONE;
248             gbc.weightx = 0;
249             gbc.weighty = 0;
250             gbc.insets = new Insets(12, 12, 5, 12);
251             add(virtualKeyLabel, gbc);
252
253             gbc = new GridBagConstraints();
254             gbc.gridx = 1;
255             gbc.gridy = 0;
256             gbc.gridwidth = 1;
257             gbc.fill = gbc.HORIZONTAL;
258             gbc.weightx = 1.0;
259             gbc.weighty = 0;
260             gbc.insets = new Insets(12, 0, 5, 11);
261             add(_virtualKey = new JComboBox(), gbc);
262             _virtualKey.getAccessibleContext().setAccessibleDescription(
263                 bundle.getString("ACSD_VirtualKey")); // NOI18N
264

265             JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
266             _ctrl = new JCheckBox();
267             Mnemonics.setLocalizedText(_ctrl, bundle.getString("CTL_Ctrl")); // NOI18N
268
_ctrl.getAccessibleContext().setAccessibleDescription(
269                 bundle.getString("ACSD_CtrlKey")); // NOI18N
270
panel.add(_ctrl);
271             _alt = new JCheckBox();
272             Mnemonics.setLocalizedText(_alt, bundle.getString("CTL_Alt")); // NOI18N
273
_alt.getAccessibleContext().setAccessibleDescription(
274                 bundle.getString("ACSD_AltKey")); // NOI18N
275
panel.add(_alt);
276             _shift = new JCheckBox();
277             Mnemonics.setLocalizedText(_shift, bundle.getString("CTL_Shift")); // NOI18N
278
_shift.getAccessibleContext().setAccessibleDescription(
279                 bundle.getString("ACSD_ShiftKey")); // NOI18N
280
panel.add(_shift);
281             virtualKeyLabel.setLabelFor(_virtualKey);
282             
283             gbc = new GridBagConstraints();
284             gbc.gridx = 2;
285             gbc.gridy = 0;
286             gbc.gridwidth = 1;
287             gbc.fill = gbc.NONE;
288             gbc.weightx = 0;
289             gbc.weighty = 0;
290             gbc.insets = new Insets(12, 0, 5, 12);
291             add(panel, gbc);
292             
293             JLabel keyStrokeLabel = new JLabel();
294             Mnemonics.setLocalizedText(keyStrokeLabel, bundle.getString("CTL_KeyStroke")); // NOI18N
295

296             gbc = new GridBagConstraints();
297             gbc.gridx = 0;
298             gbc.gridy = 1;
299             gbc.gridwidth = 1;
300             gbc.anchor = gbc.WEST;
301             gbc.fill = gbc.NONE;
302             gbc.weightx = 0;
303             gbc.weighty = 0;
304             gbc.insets = new Insets(0, 12, 0, 12);
305             add(keyStrokeLabel, gbc);
306
307             gbc = new GridBagConstraints();
308             gbc.gridx = 1;
309             gbc.gridy = 1;
310             gbc.gridwidth = 2;
311             gbc.fill = gbc.HORIZONTAL;
312             gbc.weightx = 1.0;
313             gbc.weighty = 0;
314             gbc.insets = new Insets(0, 0, 0, 11);
315             add(_keyGrabber = new KeyGrabberField(), gbc);
316             _keyGrabber.getAccessibleContext().setAccessibleDescription(
317                 bundle.getString("ACSD_KeyStroke")); // NOI18N
318
keyStrokeLabel.setLabelFor(_keyGrabber);
319
320             _keyGrabber.addActionListener(new ActionListener() {
321                 public void actionPerformed(ActionEvent ev) {
322                     setAsText(_keyGrabber.getText());
323                 }
324             });
325             
326             getAccessibleContext().setAccessibleDescription(
327                 bundle.getString("ACSD_KeyStrokeCustomEditor")); // NOI18N
328

329             // fill in virtual key list
330

331             if (_virtualKeys == null) {
332                 java.util.List JavaDoc list = new ArrayList();
333
334                 Field[] fields = KeyEvent.class.getDeclaredFields();
335                 for (int i = 0; i < fields.length; i++) {
336                     Field f = fields[i];
337                     int modifiers = f.getModifiers();
338                     if (Modifier.isPublic(modifiers)
339                         && Modifier.isStatic(modifiers)
340                         && Modifier.isFinal(modifiers)
341                         && f.getType() == Integer.TYPE
342                         && f.getName().startsWith("VK_")) { // NOI18N
343
list.add(f.getName());
344                     }
345                 }
346                 _virtualKeys = new String JavaDoc[list.size()];
347                 for (int i = 0; i < list.size(); i++) {
348                     _virtualKeys[i] =(String JavaDoc) list.get(i);
349                 }
350             }
351             _virtualKey.addItem(""); // NOI18N
352
for (int i = 0; i < _virtualKeys.length; i++)
353                 _virtualKey.addItem(_virtualKeys[i]);
354
355             KeyStroke key =(KeyStroke) getValue();
356             if (key != null)
357                 setKeyStroke(key);
358
359             // listeners
360

361             ItemListener il = new ItemListener() {
362                 public void itemStateChanged(ItemEvent e) {
363                     virtualKeyChanged();
364                 }
365             };
366             _virtualKey.addItemListener(il);
367             _ctrl.addItemListener(il);
368             _alt.addItemListener(il);
369             _shift.addItemListener(il);
370         }
371
372         java.awt.Component JavaDoc getKeyGrabber() {
373             return _keyGrabber;
374         }
375
376         private void setKeyStroke(KeyStroke key) {
377             _ctrl.setSelected(0 !=(InputEvent.CTRL_MASK & key.getModifiers()));
378             _alt.setSelected(0 !=(InputEvent.ALT_MASK & key.getModifiers()));
379             _shift.setSelected(0 !=(InputEvent.SHIFT_MASK & key.getModifiers()));
380
381             int keycode = key.getKeyCode();
382             String JavaDoc keyName = getVirtualkeyName(keycode);
383             if (keyName != null) {
384                 _virtualKey.setSelectedItem(keyName);
385                 _keyGrabber.setText(getAsText());
386             }
387         }
388
389         private void virtualKeyChanged() {
390             String JavaDoc keyName =(String JavaDoc) _virtualKey.getSelectedItem();
391             if ("".equals(keyName)) { // NOI18N
392
_keyGrabber.setText(""); // NOI18N
393
setValue(null);
394                 return;
395             }
396
397             try {
398                 Field f = KeyEvent.class.getDeclaredField(keyName);
399                 int keycode = f.getInt(KeyEvent.class);
400                 int mods = 0;
401                 if (_ctrl.isSelected())
402                     mods |= InputEvent.CTRL_MASK;
403                 if (_shift.isSelected())
404                     mods |= InputEvent.SHIFT_MASK;
405                 if (_alt.isSelected())
406                     mods |= InputEvent.ALT_MASK;
407
408                 setValue(KeyStroke.getKeyStroke(keycode, mods));
409                 _keyGrabber.setText(getAsText());
410             }
411             catch (NoSuchFieldException JavaDoc ex) {
412                 ex.printStackTrace(); // should not happen
413
}
414             catch (IllegalAccessException JavaDoc ex) {
415                 ex.printStackTrace(); // should not happen
416
}
417         }
418
419         private class KeyGrabberField extends JTextField {
420             protected void processKeyEvent(KeyEvent e) {
421                 if (e.getKeyCode() == KeyEvent.VK_TAB)
422                     super.processKeyEvent(e);
423                 else if (e.getID() == KeyEvent.KEY_PRESSED) {
424                     int keycode = e.getKeyCode();
425                     if (keycode != KeyEvent.VK_CONTROL
426                         && keycode != KeyEvent.VK_ALT
427                         && keycode != KeyEvent.VK_SHIFT) {
428                         KeyStroke key = KeyStroke.getKeyStroke(keycode, e.getModifiers());
429                         setKeyStroke(key);
430                     }
431                     e.consume();
432                 }
433             }
434         }
435     }
436 }
437
Popular Tags