在强行滚动之前检查屏幕上是否显示一行?

Bra*_*rad 7 java swing scroll jtable

我正在使用Swing JTable,我想强制滚动到其中的特定行.这很简单,使用scrollRowToVisible(...),但是我想首先检查这个行在滚动到它之前是否已经在屏幕上看不到,好像它已经可见,不需要强制滚动.

我怎样才能做到这一点 ?

mdm*_*dma 3

下面的链接指向一篇确定单元格是否可见的文章。您可以使用它 - 如果单元格可见,则该行可见。(但当然,如果也存在水平滚动,则可能不是整行。)

但是,我认为当单元格比视口宽时,这会失败。要处理这种情况,您可以更改测试以检查单元格边界的顶部/底部是否在视口的垂直范围内,但忽略单元格的左/右部分。最简单的方法是将矩形的左侧和宽度设置为 0。我还更改了方法以仅获取行索引(不需要列索引),并且true如果表不在视口中,则返回,这似乎更好地与您的用例保持一致。

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); 
} 
Run Code Online (Sandbox Code Playgroud)