我想知道如何确定是否触发了控件的KeyCombination(通过Mnemonic构建)。或者为了简单起见,还有助记符的处理方法?
基本上,我正在使用从Labeled
及其Behavior
类扩展的自定义控件,我想在触发指定的助记符时执行一些额外的操作。
所以经过一番挖掘后,我想出了一个简单的想法,就是从KeyEvent
听取Scene
(但请注意,这只是一个想法。无论如何,我和#39 ;稍后会弄明白其余部分)。以下是:
public CustomLabeledBehavior(CustomLabeled control) {
super(control, ...);
/* IMPORTANT PART */
// Assume that mnemonicParsing is set to true
TextBinding tb = new TextBinding(control.getText());
KeyCombination kc = tb.getMnemonicKeyCombination();
control.getScene().addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if (kc.match(e)) {
System.out.println("MATCHED!");
}
});
}
答案 0 :(得分:0)
为了使这个答案比以前更有用,我将向您展示我目前用于确定KeyCombination
是否被触发的方法的用法。如果可以的话,我会尽力解释每一个细节。
我们只关注使用自定义控件的Mnemonic
属性添加MnemonicParsing
。我们将此自定义控件称为CustomLabeled
,因为基于该问题,它从Labeled
类扩展,因此名称基于它。然后我们将在名为Skin
的{{1}}类中进行处理。
#1 初始化控件:
CustomLabeledSkin
#2 设置我们的<!-- Assuming that this FXML is already set and is attached to a Scene -->
<CustomLabeled text="_Hello World!" mnemonicParsing="true"/>
:
MnemonicHandler
#3 初始化我们的Skin类:
/* 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();
}
}
}
注意:
/** * 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); }
类不是公共API的一部分,TextBinding
节点使用它来处理助记符。
此外,如果没有分配当前的助记符,您可以创建一个分离Labeled
的方法(例如,之前有助记符,然后代码已更改......)。