我在扩展 JTree 节点时遇到问题。当使用选择一个节点时,我开始除了所选节点的路径和要折叠的所选节点本身之外的所有内容。我试过使用
tree.collapsePath(new TreePath(tree.getModel().getRoot()));
tree.expandPath(new TreePath(e111.getPath()));
像这样的东西,但它似乎没有效果,我真的不知道我该怎么做
这是我的树的样子:
http://img220.imageshack.us/img220/3450/jtreepng.png
如果我单击 1.1.1,我希望其他所有内容都被折叠,但 1.1.1 节点和路径中的元素。
这是我创建的应用程序:
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()));
}
编辑:奇怪的是tree.collapsePath
作品很好,似乎 tree.expandPath(new TreePath(e111.getPath()));
是问题所在