【问题标题】:Adding dynamic entries to Menu in JavaFX在 JavaFX 中向菜单添加动态条目
【发布时间】:2016-03-22 08:30:16
【问题描述】:

我正在尝试向 JavaFX 菜单动态添加条目。我有一个可以绘制图形的程序,每次绘制新图形时,我都会在 ObservableList 中添加一个条目,其中包含所有图形。
我的controller 观察列表,并且在每次更改时,它都应该修改JavaFX view 中的Menu。但是,这样做时我遇到了问题。
在第一次添加时,它按预期显示the first entry
在第二次添加时,列表包含the first entry + the first entry + the last entry
在第三次添加时它显示first entry + the first entry + the second entry + the first entry + the second entry + the last entry。我想你可以从这一点开始猜出模式。
这段代码 sn-p 取自我的控制器:

graphHandler.getGraphs().addListener(new ListChangeListener<Graph>() {
//GraphHandler.class is my model, that holds the list with all graphs
    @Override
    public void onChanged(Change<? extends Graph> c) {
        Menu history = graphView.getHistoryMenu();
        history.getItems().removeAll();
        //on change get the Menu from the model and empty it
        String changes = (String) c.toString();
        System.out.println(changes);
        //Output will be added below snippet
        graphHandler.getGraphs().forEach((Graph graph) -> {
            String root = graph.getRootNode().toString();
            MenuItem item = new MenuItem(root);
            //Get the graph's root node name and add a MenuItem with it's name
            item.setOnAction(new EventHandler<ActionEvent>() {
            //On choosing a MenuItem load the according graph; works fine
                @Override
                public void handle(ActionEvent event) {
                    graphHandler.getGraphByRootNode(root);
                }
            });
            history.getItems().addAll(item);
            //Add all MenuItems to the Menu
        });
    }
});

我的方法是在每次更改时清空Menu 并重新填充它,但它似乎不起作用。有人知道我缺少什么吗?

{ [com.example.d3project.model.Graph@7eb5106] added at 0 }
{ [com.example.d3project.model.Graph@f510ff2] added at 1 }
{ [com.example.d3project.model.Graph@69239a8d] added at 2 }

输出显示了我期望看到的内容。 ObservableListsize() 也是我所期待的。

【问题讨论】:

    标签: java javafx menu menuitem


    【解决方案1】:

    您正在使用removeAll(E...),您需要在其中传递要删除的对象。由于您没有传递任何参数,因此不会删除任何内容。要清除列表,请使用clear(),它将删除历史列表中的所有项目。

    【讨论】:

    • 曾经尝试将graphHandler.getGraphs() 作为参数传递,但没有成功。感谢您的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2020-05-27
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多