views:

86

answers:

1

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 ?

+1  A: 

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); 
} 
mdma
Well, this solution at least has put me on the right road, here's what worked for me :JViewport viewport = scrollPane1.getViewport();Rectangle rect = myTable.getCellRect( rowToSelect, 1, true ); if( !viewport.contains( rect.getLocation() ) ) myTable.scrollRowToVisible( rowToSelect );. . . Thanks a lot
Brad