如何禁用JavaFX MenuBar的助记符? [英] How to disable mnemonic for JavaFX MenuBar?

查看:108
本文介绍了如何禁用JavaFX MenuBar的助记符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的舞台上,我像往常一样在程序顶部插入了一个菜单栏.我想在舞台上的其他上下文中为ALT键(以及箭头键)提供一些逻辑.但是每次我按下ALT和箭头时,我也会无意间浏览菜单栏的菜单.

In my stage I have inserted a menubar at the top like usual for programs. I want to give the ALT key (together with arrow keys) some logic in another context within the stage. But everytime I press ALT and arrows I unintentionally navigate through the menus of the menubar, too.

我想避免这种情况,或者最好完全禁用此助记符行为. 将所有菜单的mnemonicParsing属性设置为false失败.我也尝试过这种方法但没有成功:

I want to avoid that or better completely disable this mnemonic behavior. Setting the mnemonicParsing properties of all menus to false failed. I also tried this approach without success:

menubar.addEventFilter(KeyEvent.ANY, e -> e.consume());

推荐答案

在按下 ALT 时,第一个菜单获得焦点,并且当菜单具有焦点时,箭头键会在其中导航,而 ALT 是否按下.因此,为了防止出现这种情况,您需要防止在按 ALT 时第一个菜单获得焦点.

When ALT is pressed first menu gets focus and when menus have focus, arrow keys cause navigation among them whether ALT is pressed or not. So in order to prevent this behavior you need to prevent first menu getting focus when ALT is pressed.

查看MenuBarSkin类的构造函数源代码,即可找到解决方案:

Looking at the MenuBarSkin class' constructor source code, gives us the solution:

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添加到scene而不是menubar:


Solution:

As you had already guessed, solution is to consume the event when ALT is down but you need to add the EventHandler to the scene not menubar:

scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        // your desired behavior
        if(event.isAltDown())
            event.consume();
    }
});

这篇关于如何禁用JavaFX MenuBar的助记符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆