寻找如何遍历JTree(可以做到),并检查每个节点是否显示(对用户可见)。无法相信JTree没有这个功能,也许我错过了什么?
您必须考虑两件不同的事情:
一个节点可能因为关闭其中一个父节点而变得隐藏。即使父节点在屏幕上可见,子节点也不会显示。使用JTree.isVisible()来解决这个问题。
如果节点已展开,则可能因为滚动出了当前视口而被隐藏。这不是在JTree中处理的,而是在包装树的JScrollPane中处理的。要找出节点是否在视口的可见区域内,请执行以下操作:
要查看#2是否正确,您必须使用JTree.getPathBounds()获取节点所在的矩形。然后,您必须将此矩形与视口相交(使用scrollPane.getViewport().getViewRect()
)。如果nodeRect.intersects(viewRect)
返回true
,则该节点可见。
根据您的应用程序,只查找可见节点可能比迭代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);
}
}