JavaFX:每次显示菜单时,更新菜单子项 [英] JavaFX: Update menu sub-items everytime menu shown

查看:136
本文介绍了JavaFX:每次显示菜单时,更新菜单子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每次在扩展菜单之前都要更新菜单的子项. 这就是我尝试过的:

I want to have the subitems of a menu every time updated, before the menu is expanded. This is what i tried:

@FXML javafx.scene.control.Menu menu;

public void initiallize(){
// ...

this.menu.setOnAction((event) -> {
                this.menu.getItems().clear();
                this.menu.getItems().add(new MenuItem("Hello"));
                this.menu.getItems().add(new MenuItem("World"));
                this.menu.getItems().add(new MenuItem("!!!!!"));
            });
}

它接近但不正确.仅在单击该项目后才进行更新.菜单可能会展开,但带有旧值.使用setOnShown()代替 setOnAction()也不起作用,因为在显示此消息时为时已晚.

It is close but not correct. The update only happens after a click on the item. The menu might expand but with old values. Trials using setOnShown() instead of setOnAction() were also not working, since at the time of Showing it is too late for an update.

该如何纠正?

这似乎可行:

this.menu.getParentMenu().setOnShowing((event) -> {
                    this.menu.getItems().clear();
                    this.menu.getItems().add(new MenuItem("Hello"));
                    this.menu.getItems().add(new MenuItem("World"));
                    this.menu.getItems().add(new MenuItem("!!!!!"));
                });

这是最好的方法还是有更好的解决方案(不访问ParentMenu)?

Is this the best way or are there better solutions (w/o accessing the ParentMenu)?

推荐答案

此菜单是MenuBar的子级吗?如果是这样,您肯定必须单击菜单之一才能进入MenuItems.您可以通过以下操作在点击发生之前更新MenuItems:

Are this Menus Children of a MenuBar? If so you definetely have to click one of the Menus to get to the MenuItems. You can update the MenuItems before the click happens by doing this:

this.menu.setOnMouseEntered(event -> {
    this.menu.getItems().add(new MenuItem("Test"));
});

通过这种方式,每当鼠标光标位于菜单本身上时,便会更新MenuItems.

By this you are updating the MenuItems everytime the mouse cursor is on the Menu itself.

这篇关于JavaFX:每次显示菜单时,更新菜单子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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