简体   繁体   中英

How to refresh a TreeItem's nodes in JavaFX?

I have a TreeView that displays a list of servers and a list of databases under each server, so it looks something like this:

-localhost
---database1
---database2
---database3
-remotehost
---database4
---database5
---database6

The databases in each server are not populated until the treeitem of that server is selected(to save load time). Now, when a different server becomes selected, I want to refresh the list of databases on that newly selected server. Currently, my script only adds the list of dbs to the newly selected server but doesn't remove the dbs that were already there, even though I have the script to remove them in place. What am I doing wrong?

connTree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
    @SuppressWarnings("unchecked")
    @Override
    public void changed(
        ObservableValue<? extends TreeItem<String>> observable,
        TreeItem<String> old_val, TreeItem<String> new_val) {
        TreeItem<String> selectedItem = new_val;
        String selectedHost = selectedItem.getValue();
        if (selectedHost != "test") {
            if (conns.exists(selectedHost)) {
                selectedServer = conns.get(selectedHost);
                selectedServer.getDatabases();
                List<String> dbs = selectedServer.databases;
                TreeItem<String> c = connTree.getSelectionModel().getSelectedItem();
                c.getChildren().removeAll(c); //This should do what I want, right?
                for (String db: dbs) {
                    Button dbIcon = new Button("", new Glyph("FontAwesome", "DATABASE"));
                    dbIcon.setBackground(Background.EMPTY);
                    TreeItem<String> branch = new TreeItem<String>(db, dbIcon);
                    branch.setExpanded(true);
                    selectedItem.getChildren().add(branch);
                }
            }
        }   
    }
});

I dont get any errors. The nodes are just never removed. Thanks in advance.

Strangely enough, selectedItem.getChildren().clear() did the trick. I'm not sure what the difference between clear() and removeAll() is, but clear() works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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