문제

I want to implement a requirement where in I have to collapse all child nodes of JTree.

I am using jdk1.6.

Note: Only the child nodes of root element are to be collapsed on button click.

Here is my code:

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); 
}
도움이 되었습니까?

해결책

If I understand your requirement you might be able to use the following code:

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);
  }
}

다른 팁

Try this:

for(int i = jTree.getRowCount() - 1; i >= 0; i--){
     jTree.collapseRow(i);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top