문제

I created a form with default NetBeans edito and put a jTree on it. It somehow then creates bunch of elements such as "colors", "sports", "food" in there. But it is not in the creation code. Where is it coming from and how can I edit it...

Even if I do jTree1.removeAll(); everything is still there... and non of my code for adding new items to the jTree working.

private void test(java.awt.event.MouseEvent evt) {
    //trying to remove all, but it does not remove anything
    jTree1.removeAll();

    //it does print it in debug meaning that this function is called
    System.out.println("qwe");

    //create the root node
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    //create the child nodes
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

    //add the child nodes to the root node
    root.add(child1);
    root.add(child2);

    //now how do I add it to the tree?
    //???
}

I need to be able to edit jTree contents at runtime.

도움이 되었습니까?

해결책

Problem in next you create your JTree like this JTree tree = new JTree() (according to docs) it has sample nodes. Add next lines after you create your nodes(root,child1,child2) and all will be work:

DefaultTreeModel model =(DefaultTreeModel) jTree1.getModel();
model.setRoot(root);

Also you needn't to call jTree1.removeAll(); it is used for other purposes.(docs)

Read tutorial for JTree

다른 팁

Initialize your JTree inside the custom GUI initializer createUIComponents() method.

To create custom GUI initializer source code for a certain component, follow this general procedure:

  1. Select the desired component.

  2. In the Inspector, check the option Custom Create.

  3. In the text editor, locate the method createUIComponents(), and type the desired source code. The code in this method will not be removed on compilation.

Full explanation: https://www.jetbrains.com/help/idea/creating-form-initialization-code.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top