【发布时间】: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 }
输出显示了我期望看到的内容。 ObservableList 的 size() 也是我所期待的。
【问题讨论】: