Java JTree - How to check if node is displayed?

Look for how to get through JTree (you can do it) and check that each node displays whether it is displayed (to the user) or not displayed. I canโ€™t believe that JTree does not have this function, maybe I am missing something?

+3
source share
2 answers

You should consider two different things:

  • A node can become hidden by closing one of its parents. Although the parent is displayed on the screen, the child is not. To do this, use JTree.isVisible () .

  • node , , viewport. JTree, JScrollPane, . , node .

, # 2 , , node JTree.getPathBounds(). ( scrollPane.getViewport().getViewRect(). nodeRect.intersects (viewRect) true, node.

+5

, 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);
    }   
}
+2

Source: https://habr.com/ru/post/1745177/


All Articles