View Javadoc

1   /*
2    *  XNap Commons
3    *
4    *  Copyright (C) 2005  Steffen Pingel
5    *
6    *  This library is free software; you can redistribute it and/or
7    *  modify it under the terms of the GNU Lesser General Public
8    *  License as published by the Free Software Foundation; either
9    *  version 2.1 of the License, or (at your option) any later version.
10   *
11   *  This library is distributed in the hope that it will be useful,
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   *  Lesser General Public License for more details.
15   *
16   *  You should have received a copy of the GNU Lesser General Public
17   *  License along with this library; if not, write to the Free Software
18   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  package org.xnap.commons.settings;
21  
22  import java.awt.event.KeyEvent;
23  import java.util.StringTokenizer;
24  import javax.swing.KeyStroke;
25  
26  /***
27   * Provides a setting for <code>KeyStroke</code> objects.
28   */
29  public class KeyStrokeSetting extends AbstractSetting<KeyStroke> {
30  
31      public KeyStrokeSetting(SettingResource backend, String key, KeyStroke defaultValue, Validator validator)
32      {
33      	super(backend, key, defaultValue, validator);
34      }
35  
36      public KeyStrokeSetting(SettingResource backend, String key, KeyStroke defaultValue)
37      {
38      	super(backend, key, defaultValue, null);
39      }
40  
41      protected KeyStroke fromString(String value)
42  	{
43  		// this could be way easier but there seems to be no serialize
44  		// method that can create the format recognized by getKeyStroke()
45  		//return KeyStroke.getKeyStroke(key);
46  
47  		StringTokenizer t = new StringTokenizer(value, ARRAY_SEPARATOR);
48  		if (t.countTokens() >= 3) {
49  			try {
50  				int keyCode = Integer.parseInt(t.nextToken());
51  				int modifiers = Integer.parseInt(t.nextToken());
52  				Character character = new Character(t.nextToken().charAt(0));
53  				return (keyCode == KeyEvent.VK_UNDEFINED)
54  					? KeyStroke.getKeyStroke(character, modifiers)
55  					: KeyStroke.getKeyStroke(keyCode, modifiers);
56  			}
57  			catch (NumberFormatException e) {
58  			}
59  		}
60  
61  		return null;
62  	}
63  
64  	protected String toString(KeyStroke value)
65  	{
66  		KeyStroke keystroke = (KeyStroke)value;
67  		
68  		// encode keystroke
69  		StringBuilder sb = new StringBuilder();
70  		sb.append(keystroke.getKeyCode());
71  		sb.append(ARRAY_SEPARATOR);
72  		sb.append(keystroke.getModifiers());
73  		sb.append(ARRAY_SEPARATOR);
74  		sb.append(keystroke.getKeyChar());
75  		return sb.toString();
76  	}
77  
78  }