I have a TreeView
and a Button
in my program. Whenever this Button
is clicked, it adds a new element right after the element selected last in the TreeView.
For example, if I were to select the "Test Action" element and click the "Add" button, it should add another TreeItem
right after "Test Action", but before "Test Condition".
I've written code so that I can keep track of the element selected last:
@FXML
TreeView<String> view;
TreeItem<String> current = root;
view.selectionModelProperty().addListener(new ChangeListener<MultipleSelectionModel<TreeItem<String>>>() {
@Override
public void changed(ObservableValue<? extends MultipleSelectionModel<TreeItem<String>>> observable,
MultipleSelectionModel<TreeItem<String>> oldValue,
MultipleSelectionModel<TreeItem<String>> newValue) {
current = newValue.getSelectedItem();
}
});
However, through the use of the TreeItem, "current", there is no method I can use to find its index in the TreeView.
This is so that I can do:
root.getChildren().add(index, new TreeItem<String>(new OpenBank().getAction(), Icons.ACTION.getIcon()));
So is there a way to find a child's index in a TreeView
?
Best Answer
The class
TreeItem
has a methodgetParent
, which returns the parent of the specifiedTreeItem
. This parent, which is also aTreeItem
has a methodgetChildren
to get the childTreeItem
s; the order ofTreeItem
s in the returnedObservableList
is the actual order that you can see on the screen, therefore you can insert a new element in a specific index withadd
after you retrieved the index of the element in the list withindexOf()
.You can simply handle the current selection in the event listener of your
Button
:If you already tracking the current selection:
The modification is just to use
current
(that's how you named your variable) rather than getting the selection in the handler: