Search code examples
javaswingjtree

Cannot load the nodes jTree using Java netbeans


this is the first time i am using jtree using java. but i couldn't load it when i tried load it it shown as blank.i dont know how to load it.what i tried so far i attached below.please give me the solution for it thanks. JTree name is jTree1

DefaultTreeModel root1;
     DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); 
        public void Load()
        {
            DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables");
            vegetableNode.add(new DefaultMutableTreeNode("Capsicum"));
            vegetableNode.add(new DefaultMutableTreeNode("Carrot"));
            vegetableNode.add(new DefaultMutableTreeNode("Tomato"));
            vegetableNode.add(new DefaultMutableTreeNode("Potato"));
            DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits");
            fruitNode.add(new DefaultMutableTreeNode("Banana"));
            fruitNode.add(new DefaultMutableTreeNode("Mango"));
            fruitNode.add(new DefaultMutableTreeNode("Apple"));
            fruitNode.add(new DefaultMutableTreeNode("Grapes"));
            fruitNode.add(new DefaultMutableTreeNode("Orange")); 
            root.add(vegetableNode);
            root.add(fruitNode); 
            root1 = (DefaultTreeModel)jTree1.getModel();
        }

Solution

  • You need to add the tree to the root, then add the tree to the JTree:

    root1 = (DefaultTreeModel)jTree1.getModel();
    

    To:

    root1.setRoot(root);
    jTree1.setModel(root1);
    

    See the setModel() documentation.