2012-04-10 75 views

回答

8

您應該使用getLevelgetLevel返回此節點上方的層級數 - 從根節點到此節點的距離。如果此節點是根,則返回0.或者,如果出於任何原因,您已獲得Treenode[]路徑(使用getPath()),那麼獲取該數組的長度就足夠了。

getDepth是不同的,因爲它返回以此節點爲根的樹的深度。這不是你想要的。

+0

謝謝匿名。 – 2012-04-10 12:28:48

3

basicaly你必須IterateJTree,但TreeSelectionListener可以返回有趣的值,例如

import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTree; 
import javax.swing.SwingUtilities; 
import javax.swing.event.TreeSelectionEvent; 
import javax.swing.event.TreeSelectionListener; 

public class TreeSelectionRow { 

    public TreeSelectionRow() { 
     JTree tree = new JTree(); 
     TreeSelectionListener treeSelectionListener = new TreeSelectionListener() { 

      @Override 
      public void valueChanged(TreeSelectionEvent treeSelectionEvent) { 
       JTree treeSource = (JTree) treeSelectionEvent.getSource(); 
       System.out.println("Min: " + treeSource.getMinSelectionRow()); 
       System.out.println("Max: " + treeSource.getMaxSelectionRow()); 
       System.out.println("Lead: " + treeSource.getLeadSelectionRow()); 
       System.out.println("Row: " + treeSource.getSelectionRows()[0]); 
      } 
     }; 
     tree.addTreeSelectionListener(treeSelectionListener); 
     String title = "JTree Sample"; 
     JFrame frame = new JFrame(title); 
     frame.add(new JScrollPane(tree)); 
     frame.setSize(300, 150); 
     frame.setVisible(true); 
    } 

    public static void main(String args[]) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       TreeSelectionRow treeSelectionRow = new TreeSelectionRow(); 
      } 
     }); 
    } 
} 
+0

哇,有趣的功能!我將使用匿名建議的getLevel(),但也要謝謝你,它可以派上用場:) – 2012-04-10 12:29:58