Java JTree-如何检查是否显示节点?
查看如何遍历JTree(可以做到这一点),并查看每个节点,查看它是否显示(对用户)或不可见。不敢相信JTree没有这个功能,也许我遗漏了什么东西? < P>你必须考虑两个不同的事情:Java JTree-如何检查是否显示节点?,java,swing,jtree,Java,Swing,Jtree,查看如何遍历JTree(可以做到这一点),并查看每个节点,查看它是否显示(对用户)或不可见。不敢相信JTree没有这个功能,也许我遗漏了什么东西? < P>你必须考虑两个不同的事情: 节点可以通过关闭其父节点之一而隐藏。即使父对象在屏幕上可见,子对象也不可见。用于此 如果节点被展开,它可能会被隐藏,因为它已从当前节点中滚动出来。这不是在JTree中处理的,而是在包装树的中处理的。以确定节点是否位于视口的可见区域中 要确定#2是否为真,必须获取节点使用的矩形。然后,必须将此矩形与视口相交(使用sc
要确定#2是否为真,必须获取节点使用的矩形。然后,必须将此矩形与视口相交(使用
scrollPane.getViewport().getViewRect()
。如果nodpright.intersects(viewRect)
返回true
,节点可见。根据您的应用程序,只查找可见节点可能更有效,而不是遍历树模型中的所有节点并确定每个节点是否可见。执行此操作的示例函数如下所示:
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);
}
}
导入java.awt.Rectangle;
导入java.util.ArrayList;
导入java.util.List;
导入javax.swing.JScrollPane;
导入javax.swing.JTree;
导入javax.swing.tree.TreeNode;
导入javax.swing.tree.TreePath;
公共类jtree工具{
公共静态列表getVisibleNodes(JScrollPane hostingScrollPane,JTree hostingJTree){
//在滚动窗格中查找第一行和最后一行。
最终矩形visibleRectangle=hostingScrollPane.getViewport().getViewRect();
final int firstRow=hostingJTree.getClosestRowForLocation(visibleRectangle.x,visibleRectangle.y);
final int lastRow=hostingJTree.getClosestRowForLocation(visibleRectangle.x,visibleRectangle.y+visibleRectangle.height);
//遍历每个可见行,标识此行的对象,并将其添加到结果列表中。
List resultList=new ArrayList();
对于(int currentRow=firstRow;currentRowDammnn),我知道这与视口有关。谢谢!