我想实现一个要求,我必须折叠JTree
的所有子节点。
我正在使用 jdk1.6。
注意:只需在按钮单击时折叠根元素的子节点。
这是我的代码:
private static void collapseAll(JTree tree, TreePath parent) {
TreeNode node = (TreeNode)parent.getLastPathComponent();
if (!node.isLeaf() && node.getChildCount()>=0) {
Enumeration e = node.children();
while (e.hasMoreElements()) {
TreeNode n = (TreeNode)e.nextElement();
TreePath path = parent.pathByAddingChild(n);
collapseAll(tree, path);
}
}
tree.collapsePath(parent);
}
答案 0 :(得分:3)
如果我了解您的要求,您可以使用以下代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TreeCollapseTest {
private final JTree tree = new JTree();
public JComponent makeUI() {
JPanel p = new JPanel(new BorderLayout());
p.add(new JButton(new AbstractAction("collapse") {
@Override public void actionPerformed(ActionEvent e) {
// if (tree.isRootVisible()) {
int row = tree.getRowCount() - 1;
//while (row >= 0) { //collapses all nodes
while (row > 0) { //collapses only child nodes of root node
tree.collapseRow(row);
row--;
}
}
}), BorderLayout.SOUTH);
p.add(new JScrollPane(tree));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TreeCollapseTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
答案 1 :(得分:0)
尝试一下:
for(int i = jTree.getRowCount() - 1; i >= 0; i--){
jTree.collapseRow(i);
}