user2375667
user2375667

Reputation: 463

Best way to let the user choose a hotkey and then save it?

I get a KeyStroke object from a KeyEvent (from a keyPressed event with a KeyListener attached to a JTextField) that I use to create local and global shortcuts. I'm saving the keyStroke.getkeyCode() and keyStroke.getModifiers() to a file to re-create the shortcuts when the application is restarted. As I understand this, these values directly correspond to the equivalent methods of the KeyEvent class which are based on the VK_ constants.

The KeyEvent class has the following warning:

WARNING: Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.

So does that mean I shouldn't store a keyCode between sessions, because it may change in future version of Java? If so, what should I store instead? I was thinking of storing the name of the key as it is used in the VK_ constants and also used for one of the KeyStroke.getKeyStroke() methods, but I'm not sure whether that would be better and how to actually get the appropriate String.

Also I'm not quite sure how to best handle different keyboard layouts when capturing the hotkey. It seems like getKeyCode() sometimes yields an undefined code on different layouts.

Upvotes: 2

Views: 95

Answers (2)

trashgod
trashgod

Reputation: 205785

While it's likely that new key codes would represent a superset of existing codes, the user may change or add keyboards at any time. This risk may be mitigated by allowing the user to reassign keys needed for a novel keyboard layout. In this complete example, org.gcs.robot.RobotChase manages an enum Key of all keystrokes known to the application. RCKeys, seen here, displays a dialog that allows the user to reassign keys arbitrarily. RCPrefs includes methods to save and restore the chosen key code values in an instance of java.util.prefs.Preferences.

Upvotes: 2

VGR
VGR

Reputation: 44338

It's unlikely that the values will change, but yes, it is possible they might.

The easiest solution is to store the string returned by calling the KeyStroke's toString() method. That string is guaranteed to be parseable by KeyStroke.getKeyStroke(String), which is what you should call when reading the saved preference.

I think your problem with undefined key codes can be solved if you use getExtendedKeyCode() rather than getKeyCode().

Upvotes: 2

Related Questions