我在展开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()));
存在问题。
invokeLater()
,可以在这里看到:https://dev59.com/6mXWa4cB1Zd3GeqPN4qX#11260104。 - trashgod