Pass Context menu shortcuts up from editing control

前端 未结 1 1605
悲哀的现实
悲哀的现实 2020-12-12 05:41

I have a JavaFX pane (TabPane, if it matters) with a context menu associated with it. The context menu has a few shortcut keys (F2, F3) defined in it, and indeed when they a

相关标签:
1条回答
  • 2020-12-12 06:06

    I have found this roundabout solution to the problem: Add an EventFilter on the TabPane - this fires even when an editing control has focus:

    tabPane.addEventFilter(KeyEvent.KEY_PRESSED, this::keyPressed);
    

    Use this as your keyPressed function:

    private void keyPressed(KeyEvent event) {
      for (MenuItem mi : tabPane.getContextMenu().getItems())
         {
            if (mi.getAccelerator()!=null && mi.getAccelerator().match(event))
            {
                mi.getOnAction().handle(null);
                event.consume();
                return;
            }
        }
    }
    

    It is important to consume the event, so in case no editing control is selected it won't get fired twice. This obviously won't work if you have nested menus, but in my case it is a flat context menu.

    If there is anything horribly wrong with this solution, or a more straightforward way to solve this problem - please let me know!

    Edit: It may be desirable to add !mi.isDisable() to the firing condition, to avoid firing events for disabled menu items.

    0 讨论(0)
提交回复
热议问题