![](/img/trans.png)
[英]How to delete a specific TreeItem from the TreeView in javafx?
[英]JavaFX: How to find index of TreeItem in a TreeView?
我的程序中有一個TreeView
和一個Button
。 每當單擊此Button
時,它都會在 TreeView 中最后選擇的元素之后添加一個新元素。
例如,如果我要選擇“測試操作”元素並單擊“添加”按鈕,它應該在“測試操作”之后、“測試條件”之前添加另一個TreeItem
。
我編寫了代碼,以便跟蹤最后選擇的元素:
@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();
}
});
但是,通過使用 TreeItem,“當前”,我無法使用任何方法在 TreeView 中找到它的索引。
這樣我就可以做到:
root.getChildren().add(index, new TreeItem<String>(new OpenBank().getAction(), Icons.ACTION.getIcon()));
那么有沒有辦法在TreeView
中找到孩子的索引?
TreeItem
類有一個方法getParent
,它返回指定TreeItem
的父級。 這個也是TreeItem
的父級有一個方法getChildren
來獲取子TreeItem
; 返回的ObservableList
中TreeItem
的順序是您可以在屏幕上看到的實際順序,因此您可以在使用indexOf()
檢索列表中元素的索引后,使用add
在特定索引中插入新元素。
您可以在Button
的事件偵聽器中簡單地處理當前選擇:
Button b = new Button("Add");
b.setOnAction(event -> {
// Get the selected item
TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();
// If there is no selection or the root is selected do nothing
if (selectedItem == null || selectedItem == rootNode)
return;
// Otherwise get the index of the Node from the children of its parent
// and append the new item right after it
int index = selectedItem.getParent().getChildren().indexOf(selectedItem);
selectedItem.getParent().getChildren().add(index+1, new TreeItem<>("New Item"));
});
如果您已經跟蹤當前選擇:
修改只是使用current
(這就是您命名變量的方式),而不是在處理程序中獲取選擇:
Button b = new Button("Add");
b.setOnAction(event -> {
// If there is no selection or the root is selected do nothing
if (current == null || current == rootNode)
return;
// Otherwise get the index of the Node from the children of its parent
// and append the new item right after it
int index = current.getParent().getChildren().indexOf(current);
current.getParent().getChildren().add(index+1, new TreeItem<>("New Item"));
});
返回給定 TreeItem 的索引位置,假設它當前可通過樹層次結構訪問(最值得注意的是,所有父樹項都已展開)。 如果折疊了父樹項,則結果是此方法將返回 -1 以指示給定的樹項在樹中不可訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.