2010-05-12 60 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); 
    } 
}