我想知道如何确定控件的KeyCombination (通过Mnemonic构造)是否被触发。还是为了简单起见,记忆学的处理程序方法?
基本上,我使用的是从Labeled及其Behavior类扩展的自定义控件,在触发分配的Mnemonic时,我希望执行一些额外的操作。
编辑
因此,在深入研究之后,我想出了一个简单的听KeyEvent的主意(但是请注意,这只是一个想法。不管是哪种情况,我稍后都会想出其他办法的)。下面是操作步骤:
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!");
}
});
}发布于 2018-06-07 12:26:13
更新
为了使这个答案比以前更有用,我将向您展示我当前用于确定是否触发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 (例如,以前有一个助记符,然后代码被更改.)。
https://stackoverflow.com/questions/50736055
复制相似问题