I have a problem with expanding JTree nodes. I start when use selects a node everything but the path to the selected node and the selected node itself to be collapsed. I've tried using
tree.collapsePath(new TreePath(tree.getModel().getRoot()));
tree.expandPath(new TreePath(e111.getPath()));
something like this but it seems to have no effect and I really have no idea how can I do this
Here's how my tree looks:
http://img220.imageshack.us/img220/3450/jtreepng.png
If I click 1.1.1 I want everything else to be collapsed but the 1.1.1 node and the elements from the path to it.
Here's the application I've created:
public class SelectableTree extends JFrame implements TreeSelectionListener {
public static void main(String[] args) {
new SelectableTree();
}
DefaultMutableTreeNode root;
DefaultMutableTreeNode e1;
DefaultMutableTreeNode e2;
DefaultMutableTreeNode e3;
DefaultMutableTreeNode e11;
DefaultMutableTreeNode e22;
DefaultMutableTreeNode e33;
DefaultMutableTreeNode e111;
DefaultMutableTreeNode e222;
DefaultMutableTreeNode e333;
DefaultMutableTreeNode aChild;
private JTree tree;
private JTextField currentSelectionField;
public SelectableTree() {
super("JTree Selections");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
root = new DefaultMutableTreeNode("Root");
e1 = new DefaultMutableTreeNode("1");
e2 = new DefaultMutableTreeNode("2");
e3 = new DefaultMutableTreeNode("3");
e11 = new DefaultMutableTreeNode("1.1");
e22 = new DefaultMutableTreeNode("2.2");
e33 = new DefaultMutableTreeNode("3.3");
e111 = new DefaultMutableTreeNode("1.1.1");
e222 = new DefaultMutableTreeNode("2.2.2");
e333 = new DefaultMutableTreeNode("3.3.3");
root.add(e1);
root.add(e2);
root.add(e3);
e1.add(e11);
e2.add(e22);
e3.add(e33);
e11.add(e111);
e22.add(e222);
e33.add(e333);
tree = new JTree(root);
tree.addTreeSelectionListener(this);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
currentSelectionField = new JTextField("Current Selection: NONE");
content.add(currentSelectionField, BorderLayout.SOUTH);
setSize(250, 275);
setVisible(true);
}
public void valueChanged(TreeSelectionEvent event) {
tree.clearSelection();
tree.collapsePath(new TreePath(tree.getModel().getRoot()));
tree.expandPath(new TreePath(e111.getPath()));
}
Edit: strangely enough the tree.collapsePath
works just fine, it seems that tree.expandPath(new TreePath(e111.getPath()));
is the problem