JTree model update problem

D

Duane Evenson

Forgive the newbe level of this question.
I have define and declare a root node, jtree and model. I add nodes to the
model. The tree doesn't get updated.
Why?
I thought insertNodeInto fired tree updates.
I have to use model.reload() to update the tree.

TIA
Duane

Here's my test code:
//-------------------------------------
import javax.swing.*;
import javax.swing.tree.*;

public class TestTree {
public static void main(String[] args) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("top");
JTree tree = new JTree(root);
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

for (int x = 1; x <= 10; x++) {
model.insertNodeInto(new DefaultMutableTreeNode("node " + x),
root, root.getChildCount());
}

//model.reload();
JFrame frame = new JFrame();
frame.add(tree);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
 
M

m.erxleben

Hello,

the way to use the JTree is to add it into a JScrollPane
The code for this is:

JScrollPane scrollPane = new JScrollPane();
JViewPort viewPort = scrollPane.getViewport();
viewPort.add(tree);

and instead add(tree) use add(scrollPane);

Just my 0.02c

Martin
 
T

Thomas Hawtin

Duane said:
I have define and declare a root node, jtree and model. I add nodes to the
model. The tree doesn't get updated.

The tree gets updated. The problem is that a branch with no child nodes
will be closed. You need to open the branch after adding a node to it.
This is particularly annoying if you are modifying a tree, and a branch
only temporarily has no children.

DefaultMutableTreeNode root = new DefaultMutableTreeNode("top");
JTree tree = new JTree(root);
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

for (int x = 1; x <= 10; x++) {
model.insertNodeInto(new DefaultMutableTreeNode("node " + x),
root, root.getChildCount());
}

tree.expandRow(0);

Tom Hawtin
 
D

Duane Evenson

The tree gets updated. The problem is that a branch with no child nodes
will be closed. You need to open the branch after adding a node to it.
This is particularly annoying if you are modifying a tree, and a branch
only temporarily has no children.
Thanks!
Silly me, I clicked on the root node and everything showed up OK.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top