2010-05-12 57 views

回答

5

,必須考慮兩個不同的東西:

  1. 節點可以通過關閉其父母中的一方變爲隱藏。即使父母在屏幕上可見,孩子也沒有。爲此,請使用JTree.isVisible()

  2. 如果該節點已擴展,則可能會隱藏,因爲它已滾動出當前的viewport。這不是在JTree中處理,而是在包裝樹的JScrollPane中處理。瞭解節點是否位於視口的可見區域中。

要確定#2是否爲真,必須獲取節點正在使用的矩形JTree.getPathBounds()。然後,你必須交這個矩形與視(使用scrollPane.getViewport().getViewRect()。如果nodeRect.intersects (viewRect)回報true,該節點是可見的。

+0

dammmnn我知道它與視做謝謝! – Hezeus 2010-05-12 21:11:44

2

根據您的應用程序,它可能是更有效地只認準可見節點,而不是通過迭代。在TreeModel並確定是否每一個可見的所有節點如下所示的樣本函數來執行此:

import java.awt.Rectangle; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JScrollPane; 
import javax.swing.JTree; 
import javax.swing.tree.TreeNode; 
import javax.swing.tree.TreePath; 
public class JTreeTools { 
    public static List<TreeNode> getVisibleNodes(JScrollPane hostingScrollPane, JTree hostingJTree){ 
     //Find the first and last visible row within the scroll pane. 
     final Rectangle visibleRectangle = hostingScrollPane.getViewport().getViewRect(); 
     final int firstRow = hostingJTree.getClosestRowForLocation(visibleRectangle.x, visibleRectangle.y); 
     final int lastRow = hostingJTree.getClosestRowForLocation(visibleRectangle.x, visibleRectangle.y + visibleRectangle.height); 
     //Iterate through each visible row, identify the object at this row, and add it to a result list. 
     List<TreeNode> resultList = new ArrayList<TreeNode>();   
     for (int currentRow = firstRow; currentRow<=lastRow; currentRow++){ 
      TreePath currentPath = hostingJTree.getPathForRow(currentRow); 
      Object lastPathObject = currentPath.getLastPathComponent(); 
      if (lastPathObject instanceof TreeNode){ 
       resultList.add((TreeNode)lastPathObject);    
      }   
     } 
     return(resultList); 
    } 
}