简体   繁体   English

搜索并找到 TreeItem 后,我可以滚动到 TreeView 中的选定项目吗? (JavaFX)

[英]Can I scroll to selected item in TreeView after search and found TreeItem? (JavaFX)

I have a TreeView with numerous TreeItems in it.我有一个 TreeView,里面有很多 TreeItems。 I have built a search function that works and selects the TreeItem specified but the TreeView scroll function does not scroll to it so one has to do it by hand which is not convenient at all.我已经构建了一个搜索功能,该功能可以工作并选择指定的 TreeItem,但 TreeView 滚动功能不会滚动到它,因此必须手动完成,这根本不方便。 Is there a way to scroll automatically to the node (TreeItem) in some way after the search has successfully finished?搜索成功完成后,有没有办法以某种方式自动滚动到节点(TreeItem)?

Code for search function:搜索功能代码:

@FXML
private void searchButtonEvent(ActionEvent event) {
    TreeItem<String> rootItem = treeView.getRoot();
    String textFieldText;
    boolean flag = false;

    textFieldText = textField.getText();
    searchStatus.setText("");

    if (textFieldText.equals("")) {
        searchStatus.setText("Please enter something to be searched");
    } else {
        for (int i = 0; i < 2; i++) {
            for (TreeItem<String> treeItem : rootItem.getChildren().get(i).getChildren()) {
                if (treeItem.getValue().contains(textFieldText)) {
                    treeView.getSelectionModel().select(treeItem);
                    searchStatus.setText("");
                    flag = true;
                } else {
                    if (!flag) {
                        searchStatus.setText("Not found");
                    }
                }
            }
        }
    }
}

I suppose that might be a method just after我想这可能是一种方法

treeView.getSelectionModel().select(treeItem);

that might do the work.这可能会起作用。

Found the solution finally:终于找到了解决办法:

@FXML
private void searchButtonEvent(ActionEvent event) {
    TreeItem<String> rootItem = treeView.getRoot();
    String textFieldText;
    boolean flag = false;
    int count = 0;

    textFieldText = textField.getText();
    searchStatus.setText("");

    if (textFieldText.equals("")) {
        searchStatus.setText("Please enter something to be searched");
    } else {
        for (int i = 0; i < 3; i++) {
            for (TreeItem<String> treeItem : rootItem.getChildren().get(i).getChildren()) {
                count++;
                if (treeItem.getValue().contains(textFieldText)) {
                    treeView.getSelectionModel().select(treeItem);
                    treeView.scrollTo(count);
                    searchStatus.setText("");
                    flag = true;
                } else {
                    if (!flag) {
                        searchStatus.setText("Not found");
                    }
                }
            }
        }
    }
}

Method was in TreeView Class named scrollTo(int) so I just had to add a counter for that方法在名为 scrollTo(int) 的 TreeView 类中,所以我只需要为此添加一个计数器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM