Java JTree get visible row count

Description

Java JTree get visible row count

import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class Main {
   public static void main(String[] args) {
      DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      rootNode.add(a);//from w  w w.  j av a  2s.  co m

      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("2");
      a.add(a2);

      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      rootNode.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("1");
      b.add(b1);

      JTree tree = new JTree(rootNode);

      tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
   

      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new JScrollPane(tree));
      f.setSize(250, 250);
      f.setVisible(true);
    
      int s = getVisibleRowCount(tree);
      System.out.println(s);
   }

   static int getVisibleRowCount(JTree tree) {
      Rectangle visible = tree.getVisibleRect();
      int count = 0;
      for (int i = 0; i < tree.getRowCount(); i++) {
          Rectangle bounds = tree.getRowBounds(i);
          if (visible.y <= bounds.y
                  && visible.y + visible.height >= bounds.y
                          + bounds.height) {
              count++;
          }
      }
      return count;
  }
}



PreviousNext

Related