ОБНОВЛЕНИЕ
Чтобы сделать этот ответ более полезным, чем раньше, я покажу вам метод, который я использую в настоящее время, чтобы определить, запущен ли KeyCombination
.Поэтому я постараюсь объяснить каждую деталь, если смогу.
Мы сосредоточены только на добавлении Mnemonic
, используя свойство MnemonicParsing
пользовательского элемента управления.И мы назовем этот пользовательский элемент управления как CustomLabeled
, поскольку, основываясь на этом вопросе, он расширяется от класса Labeled
, следовательно, его название основано на нем.Тогда мы будем работать внутри класса Skin
, называемого CustomLabeledSkin
.
# 1 Инициализация элемента управления:
<!-- Assuming that this FXML is already set and is attached to a Scene -->
<CustomLabeled text="_Hello World!" mnemonicParsing="true"/>
# 2 Настройка нашего MnemonicHandler
:
/* These two variables are initialized from the Constructor. */
private KeyCombination kb; // The combination of keys basically, ALT + Shortcut key
private String shortcut; // The shortcut key itself basically, a Letter key
private boolean altDown = false; // Indicator if the user press ALT key
/**
* This handler is a convenience variable to easily attach
* and detach to the Scene's event handlers. This is the
* whole idea to determine whether the KeyCombination is
* triggered.
*/
private EventHandler<KeyEvent> mnemonicHandler = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
// The KeyCombination, basically, the ALT + Shortcut key.
if (kb.match(event) {
// TODO: Execute command here.
event.consume(); // Prevent from further propagation.
return; // Make sure that the rest won't be executed.
}
// While these two functions are for separate event.
// Example, pressing ALT first before the Shortcut key.
if (event.isAltDown()) altDown = !altDown;
if (altDown && event.getCode() == KeyCode.getKeyCode(shortcut)) {
// TODO: Execute command here.
event.consume();
}
}
}
# 3 Инициализация нашего класса кожи:
/**
* Constructor
*/
public CustomLabeledSkin(CustomLabeled control) {
// Since this is just an example/testing, we will only assume
// that MnemonicParsing is enabled and a valid Mnemonic is
// registered. So if you want to validate a mnemonic, you
// might want to do it here.
TextBinding tb = new TextBinding(control.getText());
kc = tb.getMnemonicKeyCombination();
shortcut = tb.getMnemonic();
// Then we can just filter for a KEY_PRESS from the Scene, then
// everything else will be handled by our MnemonicHandler.
control.getScene().addEventFilter(KeyEvent.KEY_PRESSED, mnemonicHandler);
}
ПРИМЕЧАНИЕ: Класс TextBinding
не является частью общедоступного API, он используется узлом Labeled
для обработки мнемоники.
Более того, вы можете создать метод для отсоединения MnemonicHandler
если в данный момент нет назначенной мнемоники (например, ранее была мнемоника, то код был изменен ...).