3

I have not been able to find API in the JavaFX Menu class that would allow me to retrieve the parent MenuBar. Any hints, including the usage of internal API are very welcome. (JavaFX 8)

Background: Usually any JavaFX Node can give you it's parent with the method getParent(). But since Menu and MenuItem do not inherit from Node, this possibility is not available. The MenuItem class (and therefore also the Menu class) has two similar methods:

  • getParentPopup() to get a parent ContentMenu
  • getParentMenu() to get a parent Menu

So I would have expected something like getParentMenuBar(), but it's not there.

EDIT: I just found the jira feature request for this API extension: https://bugs.openjdk.java.net/browse/JDK-8091154

Has anybody found a workaround for this?

beat
  • 1,857
  • 1
  • 22
  • 36
christoph.keimel
  • 1,240
  • 10
  • 24

1 Answers1

1

I'd question why you need access going from Menu back to MenuBar, what problem are you trying to solve?

One possible approach is to use the arbitrary properties map on Node to store a reference from Menu to MenuBar as this example shows.

public class MenuToMenuBar extends Application {
    public static void main(String args[]) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        MenuBar bar = new MenuBar();
        stage.setScene(new Scene(bar));
        Menu menu = new Menu("Foo");

        MenuItem menuItem = new MenuItem("Baz");
        menu.getItems().add(menuItem);
        bar.getMenus().add(menu);

        // put a reference back to MenuBar in each Menu
        for (Menu each : bar.getMenus()) {
            each.getProperties().put(MenuBar.class.getCanonicalName(), bar);
        }

        menuItem.setOnAction((e) -> {
            // retrieve the MenuBar reference later...
            System.out.println(menuItem.getParentMenu().getProperties().get(MenuBar.class.getCanonicalName()));
        });
        stage.show();
    }
}
Adam
  • 35,919
  • 9
  • 100
  • 137
  • Yeah, I could solve the problem by building my own mapping. Since we use fxml, we would need to do some post processing : 1) walk the scene graph and find `MenuBar` instances, then 2) hook a listener on `MenuBar.getMenus()` to save the relationships. (If you are really interested in why I need this, we should go into a private discussion about that, otherwise it would clutter the question. Of course, we are also evaluating other possible solutions, all with their own deficiencies.) – christoph.keimel Apr 01 '15 at 07:57