Search code examples
javaswingjtree

How to fill or reload a jtree in java


enter image description here

l have 2 JTrees in a frame, it happen that, for instance, if l select blue(from the left tree), it will fill the tree on the right, after that, if l now select red, the blue showing on the the right doesn't go away for red to show.

l have tried three different approaches like reloading(), repainting(), setting to null, none works.

DefaultTreeModel defMod1 = (DefaultTreeModel)jTree1.getModel();                 
defMod1.reload();
jTree1.repaint();
defMod1.setRoot(null);

What l want is for the tree on the right to be showing the content of the current selection on the left tree. That is, how can l reload or repaint the right tree to show the contents of the current selection on the left-side tree?

l use the following to get the current selection inside valueChange() of TreeSelectionListener interface which l implemented.

DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

l need a help. Thanks

PS: l have tried the solutions by DevilsHnd, but it still not working. Part of the code is below. Yes, l want a kind of clearTree() function.

@Override
public void valueChanged(TreeSelectionEvent e){
    JTree treeSource = (JTree) e.getSource();
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();//gets the selection
    if(treeSource == jTree1 ){//if it is the tree on the left
        if(node == null)//if a node is selected
    return;
        Object nodeInfo = node.getUserObject();

        if(node.isLeaf()){
        try {
            String ipp = (String)nodeInfo;
            root2 = new DefaultMutableTreeNode(InetAddress.getByName((String)nodeInfo)+ " | " + "Local Disk (C:)");//root node for the tree on the right
            selectedPcIP = InetAddress.getByName(ipp).getHostAddress();
            selectedIP = "\\\\" + selectedPcIP +"\\c$";
            ArrayList creds = new BackItDb().getCreds();//gets user name and password from the database
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",creds.get(0).toString(),creds.get(1).toString());
            try {
                SmbFile file = new SmbFile("smb://"+selectedPcIP + "/" + System.getProperty("user.home").replace('C', 'c').replace(":", "$").replaceAll("[\\\\]","/")+"/",auth);//gets the folders from the selected PC

                jTree1.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));                              
                createSecondTree(file,root2,selectedPcIP);//This is a function that creates the tree on the right(jtree2).

                jTree1.setCursor(Cursor.getDefaultCursor());
                treeModel2 = new DefaultTreeModel(root2);// treemodel for the tree on the right
                jTree2.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                jTree2.setModel(treeModel2);// the tree on the right
        }catch (UnknownHostException ex) {
            Logger.getLogger(BackIt_Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Solution

  • I could be wrong of course but it sounds like what you want is some type of clearTree() method which you would call before your method for filling the tree is called.

    This can be done with this type of method:

    /**
     * Removes all nodes from the supplied JTree except the Root.
     * 
     * @param tree (JTree) The JTree Variable Name for which to 
     * clear all nodes from.
     */
    public static void clearTree(JTree tree) {
        if (tree.toString() == null) { return; }
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        model.reload();
    }
    

    EDIT: As per OP's question in comments: "How to remove all nodes including the root?"

    To answer your question within the comment below this post, it's actually a rather simple one liner: yourTree_VariableName.setModel(null);. So, you can make another simple method like this:

    /**
     * This method will completely wipe out (clear) all nodes 
     * from a JTree including the Root node. After using this 
     * method you will need to construct another tree model to 
     * refill it.
     * 
     * @param tree (JTree) The JTree Variable Name for which to 
     * wipe all nodes from.
     */
    public static void wipeTree(JTree tree) {
        tree.setModel(null);
    }