Check if a line appears on the screen before it scrolls to it?

I am using Swing JTable and I want to force the scroll to a specific line inside it. It's simple using scrollRowToVisible (...) , but first I want to check that this line is not yet visible on the screen before scrolling to it, as if it were already visible, there is no need to force a scroll.

How can i do this?

+5
source share
1 answer

Below is a link to an article that determines whether a cell is visible. You can use this - if the cell is visible, then the row is visible. (But, of course, perhaps not the entire line if horizontal scrolling is also present.)

However, I think this will happen when the cell is wider than the viewport. To handle this case, you modify the test to check if the top / bottom border of the cell is within the vertical viewing area, but ignore the left / right side of the cell. The easiest way is to set the left and the width of the rectangle to 0. I also changed the method to take only the row index (no column index needed), and it returns trueif the table is not in the viewport, which seems to be better for your use.

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

All Articles