Arc*_*eus 5 javafx menubar keyevent mnemonics alt-key
在我的舞台上,我像往常一样为程序在顶部插入了一个菜单栏。我想在舞台的另一个上下文中给 ALT 键(连同箭头键)一些逻辑。但是每次我按 ALT 和箭头时,我也会无意中浏览菜单栏的菜单。
我想避免这种情况或更好地完全禁用这种助记符行为。将所有菜单的 mnemonicParsing 属性设置为 false 失败。我也尝试过这种方法但没有成功:
menubar.addEventFilter(KeyEvent.ANY, e -> e.consume());
Run Code Online (Sandbox Code Playgroud)
当ALT按下时,第一个菜单获得焦点,当菜单获得焦点时,无论是否ALT按下,箭头键都会在其中导航。因此,为了防止这种行为,您需要防止第一个菜单在ALT按下时获得焦点。
查看MenuBarSkin类的构造函数源代码,给了我们解决方案:
Run Code Online (Sandbox Code Playgroud)public MenuBarSkin(final MenuBar control) { ... Utils.executeOnceWhenPropertyIsNonNull(control.sceneProperty(), (Scene scene) -> { scene.getAccelerators().put(acceleratorKeyCombo, firstMenuRunnable); // put focus on the first menu when the alt key is pressed scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> { if (e.isAltDown() && !e.isConsumed()) { firstMenuRunnable.run(); } }); }); ... }
正如您已经猜到的,解决方案是在ALT关闭时使用事件,但您需要将 EventHandler 添加到scenenot menubar:
scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
// your desired behavior
if(event.isAltDown())
event.consume();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1711 次 |
| 最近记录: |