java - MenuShortcut with multiple keys
问题描述
I'm trying a bit of Java AWT and I'm trying to create a menu shortcut that requires multiple keys to be pressed (for example Alt + Space + H).
I know that by doing this:
MenuItem item= new MenuItem("Text", new MenuShortcut(KeyEvent.VK_ALT));
I can create a shortcut requiring Ctrl + Alt to be pressed. But is there a way to add more keys?
解决方案
From implementation of MenuShortcut class:
public MenuShortcut(int key) { ...
public MenuShortcut(int key, boolean useShiftModifier) { ...
This means that using MenuShortcut we can specify a maximum of three keys - Ctrl + Shift + Key.
MenuShortcut menushortcut_1 = new MenuShortcut(KeyEvent.VK_A, false); // Ctrl + A
MenuShortcut menushortcut_2 = new MenuShortcut(KeyEvent.VK_A, true); // Ctrl + Shift + A
What you could do is extend the MenuShortcut class and extend the number of keys that are accepted (very basic example, will need a bit of work):
public class MyMenuShortcut extends MenuShortcut {
int key1;
int key2;
...
public MyMenuShortcut(int key1, int key2, boolean useShiftModifier) {
super(key1, useShiftModifier);
this.key1 = key1;
this.key2= key2;
}
// toString() must be overriden to display in the menu
public String toString() {
int modifiers = 0;
if (!GraphicsEnvironment.isHeadless()) {
modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
}
if (usesShiftModifier()) {
modifiers |= Event.SHIFT_MASK;
}
return KeyEvent.getKeyModifiersText(modifiers) + "+" +
KeyEvent.getKeyText(key1) + "+" + KeyEvent.getKeyText(key2);
}
I'll leave it up to you to think about how you can accommodate for a large number of keys.
And then in your original code, you would do something like:
MenuShortcut menushortcut_3 = new MyMenuShortcut(KeyEvent.VK_C, KeyEvent.VK_B, true);