Aleksander Iksanov
Aleksander Iksanov

Reputation: 3

JTree dont update when I`m trying to add it to JFrame

When I am trying to dynamically update my JTree it works nice, but displays only my new tree. But then I am trying to add it to a JFrame - nothing happens. JTree doesnt update. And I can`t understand why.

public MainForm(){

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT");                 
    DefaultTreeModel model = new DefaultTreeModel(root);

    tree = new JTree(model);

    buildTree(model, "Node 1/Node 2/Node 3/Node 4");
    buildTree(model, "Node 1/Node 2/Node 3/Node 5");
    buildTree(model, "Node 1/Node 2/Node 3/Node 6");
    buildTree(model, "Node 1/Node 2/Node 4/Node 5");
    buildTree(model, "Node 1/Node 1/Node 3/Node 5");


    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.add(tree);
    frame.setSize(900, 600);
    frame.setVisible(true);

    //if I comment next line I`ll get just a tree in my frame (but updated 
    //as I wanted);
    //But if not I`ve got my form with buttons and tree, but tree doesn`t 
    //update
    frame.setContentPane(rootMainForm);

}

Upvotes: 0

Views: 45

Answers (1)

Antoniossss
Antoniossss

Reputation: 32535

You should add your tree to the rootMainForm as well.

This line

frame.add(tree)

adds tree to the ContentPane while this line

frame.setContentPane(rootMainForm);

overrides whole ContentPane of the frame. My bet is that you have 2 JTrees. When you comment last line, you will see most recent added component (tree here). When you uncomment it, you are overriding the whole content of frame with unknnown panel rootMainForm

Your comment makes me think, that you try to update your jtree in this line actually

 tree = new JTree(model);

Well this will create brand new JTree that is detached from GUI. If you want to update your existing JTree, just use tree.setModel(model) insteed of tree=new JTree(model)

Upvotes: 1

Related Questions