Reputation: 87
I have this code in the constructor of a subclass of a JFrame
called TreeFrame
.
I want to show 3 levels of 10 items each in the JTree. Why this works as intended:
private DefaultTreeModel treeModel;
private DefaultMutableTreeNode r;
private JTree tree;
...
r = new DefaultMutableTreeNode("ROOT");
treeModel = new DefaultTreeModel(r);
for (int i = 0; i < 10; i++) {
String a = "Object " + i;
DefaultMutableTreeNode aNode = new DefaultMutableTreeNode(a);
treeModel.insertNodeInto(aNode, r, r.getChildCount());
for (int j = 0; j < 10; j++) {
String b1 = "Sub-Object " + j;
DefaultMutableTreeNode bNode = new DefaultMutableTreeNode(b1);
treeModel.insertNodeInto(bNode, aNode, aNode.getChildCount());
for (int k = 0; k < 10; k++) {
String c = "Sub-Sub-Object " + k;
treeModel.insertNodeInto(new DefaultMutableTreeNode(c),
bNode, bNode.getChildCount());
}
}
}
tree = new JTree(treeModel);
And this does not show anything except for ROOT node? I only moved the last instruction tree = new JTree(treeModel);
before the cycle block.
private DefaultTreeModel treeModel;
private DefaultMutableTreeNode r;
private JTree tree;
...
r = new DefaultMutableTreeNode("ROOT");
treeModel = new DefaultTreeModel(r);
tree = new JTree(treeModel);
for (int i = 0; i < 10; i++) {
String a = "Object " + i;
DefaultMutableTreeNode aNode = new DefaultMutableTreeNode(a);
treeModel.insertNodeInto(aNode, r, r.getChildCount());
for (int j = 0; j < 10; j++) {
String b1 = "Sub-Object " + j;
DefaultMutableTreeNode bNode = new DefaultMutableTreeNode(b1);
treeModel.insertNodeInto(bNode, aNode, aNode.getChildCount());
for (int k = 0; k < 10; k++) {
String c = "Sub-Sub-Object " + k;
treeModel.insertNodeInto(new DefaultMutableTreeNode(c),
bNode, bNode.getChildCount());
}
}
}
Maybe it has something to do with not putting new TreeFrame()
in the EDT thread?
Upvotes: 0
Views: 51
Reputation: 347314
Both approaches are building the model just fine and all the data is all there, the problem is in the second example, the root node is collapsed by default.
Try adding tree.expandPath(new TreePath(r));
after you have completed building the model.
Upvotes: 3