【问题标题】:Java JTree - How to check if node is displayed?Java JTree - 如何检查节点是否显示?
【发布时间】:2011-02-18 20:15:52
【问题描述】:

寻找如何遍历 JTree(可以这样做)并检查每个节点以查看它是否显示(对用户)或不可见。不敢相信JTree没有这个功能,也许我错过了什么?

【问题讨论】:

    标签: java swing jtree


    【解决方案1】:

    你必须考虑两件不同的事情:

    1. 可以通过关闭其父节点之一来隐藏节点。即使父母在屏幕上可见,但孩子却不是。为此使用JTree.isVisible()

    2. 如果节点被展开,它可能会被隐藏,因为它已从当前viewport 中滚动出来。这不在 JTree 中处理,而是在包装树的 JScrollPane 中处理。找出节点是否在视口的可见区域中。

    要确定#2 是否为真,您必须获取节点使用JTree.getPathBounds() 的矩形。然后,您必须将该矩形与视口相交(使用scrollPane.getViewport().getViewRect()。如果nodeRect.intersects (viewRect) 返回true,则节点可见。

    【讨论】:

    • dammmnn 我知道这与视口有关。谢谢!
    【解决方案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);
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-10
      • 2012-06-08
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多