Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a row appears on screen before force scrolling to it?

I am using a Swing JTable, and i want to force scroll to a specific row inside it. That is simple using scrollRowToVisible(...), but i want first to check this row is not already visible on the screen before scrolling to it, as if it is already visible there is no need to force scroll.

How can i do that ?

like image 868
Brad Avatar asked May 01 '10 12:05

Brad


1 Answers

The link below is to an article that determines if a cell is visible. You could use that - if the cell is visible, then the row is visible. (But of course, possibly not the entire row, if horizontal scrolling is also present.)

However, I think this will fail when the cell is wider than the viewport. To handle this case, you change the test to check if the top/bottom of the cell bounds is within the vertical extent of the viewport, but ignore the left/right part of the cell. It is simplest to set the left and width of the rectangle to 0. I've also changed the method to take just the row index (no need for column index) and it returns true if the table is not in a viewport, which seems to align better with your use-case.

public boolean isRowVisible(JTable table, int rowIndex) 
{ 
   if (!(table.getParent() instanceof JViewport)) { 
       return true; 
    } 

    JViewport viewport = (JViewport)table.getParent(); 
    // This rectangle is relative to the table where the 
    // northwest corner of cell (0,0) is always (0,0) 

    Rectangle rect = table.getCellRect(rowIndex, 1, true); 

    // The location of the viewport relative to the table     
    Point pt = viewport.getViewPosition(); 
    // Translate the cell location so that it is relative 
    // to the view, assuming the northwest corner of the 
    // view is (0,0) 
    rect.setLocation(rect.x-pt.x, rect.y-pt.y);
    rect.setLeft(0);
    rect.setWidth(1);
    // Check if view completely contains the row
    return new Rectangle(viewport.getExtentSize()).contains(rect); 
} 
  • Determining if a cell is visible in JTable
like image 107
mdma Avatar answered Sep 26 '22 19:09

mdma