我使用fxml创建了一个treeView,然后我填充了控制器中的数据(在Initialize()中)。我添加了一个带有列表器的文本字段,当用户在其上键入内容时,我应该在树视图中搜索对应的项目并仅显示它。我不知道如何搜索或迭代树视图..这是我的代码:
@FXML private TreeView myTreeView;
@FXML public TextField searchTextField;
public Preferences myPref = Preferences.userNodeForPackage(this.getClass());
@Override
public void initialize(URL url, ResourceBundle rb) {
//root
TreeRoot = new TreeItem("TreeItems");
//1st node
material = new TreeItem("Material");
//add children to 1st node
TreeItem<String> cardsType = new TreeItem("CardsType");
TreeItem<String> memory = new TreeItem("HostMemory" );
nodes.getChildren().addAll(cardsType,memory);
//2nd node
applicationsType = new TreeItem("Application Type");
//add children to 2nd node
TreeItem<String> streamType = new TreeItem("streamTypes");
TreeItem<String> direction = new TreeItem("direction");
appsType.getChildren().addAll(streamType,direction);
//add other nodes here...
//set root and nodes
itemTreeView.setRoot(TreeRoot);
TreeRoot.getChildren().addAll(material,,applicationsType);
myTreeView.setShowRoot(false);
//save preferences
TreeRoot.setExpanded(myPref.getBoolean("TreeItems", true));
material.setExpanded(myPref.getBoolean("material", true));
applicationsType.setExpanded(myPref.getBoolean("Application Type", true));
SearchTextField.setPromptText("Search");
SearchTextField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
//we could use directly the newValue
String value = m_SearchTextField.getText();
// loop and iterate on the treeView , find items in nodes and compare with the string typed
//on the textfield
}
});
}