I'm trying to dynamically add entries to a JavaFX menu. I have a program that can draw graphs, each time a new graph is drawn, I add an entry to the an ObservableList
with all graphs.
My controller
observes the list and on each change, it should modify the Menu
in the JavaFX view
. However I'm running in a problem when doing so.
On the first add, it shows as expected the first entry
.
On the second add, the list contains the first entry + the first entry + the last entry
.
On the third add it shows the first entry + the first entry + the second entry + the first entry + the second entry + the last entry
. I guess you can guess the pattern from this point forward.
This code snippet is taken from my controller:
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
});
}
});
My approach was to empty the Menu
on every change and refill it, but it doesn't seem to work. Does anybody have an Idea what I'm missing?
{ [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 }
The output shows what I'm expecting to see. Also the size()
of the ObservableList
is as I'm expecting it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…