Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在强制滚动到某一行之前检查该行是否显示在屏幕上?_Java_Swing_Scroll_Jtable - Fatal编程技术网

Java 在强制滚动到某一行之前检查该行是否显示在屏幕上?

Java 在强制滚动到某一行之前检查该行是否显示在屏幕上?,java,swing,scroll,jtable,Java,Swing,Scroll,Jtable,我使用的是Swing JTable,我想强制滚动到其中的特定行。使用scrollRowToVisible(…)很简单,但我想先检查一下这一行在屏幕上是否可见,然后再滚动到它,就好像它已经可见一样,不需要强制滚动 我如何才能做到这一点?下面的链接指向一篇确定单元格是否可见的文章。您可以使用它-如果单元格可见,则行可见。(当然,如果还存在水平滚动,则可能不是整行。) 但是,我认为当单元格比视口宽时,此操作将失败。要处理这种情况,请更改测试以检查单元边界的顶部/底部是否在视口的垂直范围内,但忽略单元的

我使用的是Swing JTable,我想强制滚动到其中的特定行。使用scrollRowToVisible(…)很简单,但我想先检查一下这一行在屏幕上是否可见,然后再滚动到它,就好像它已经可见一样,不需要强制滚动


我如何才能做到这一点?

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

但是,我认为当单元格比视口宽时,此操作将失败。要处理这种情况,请更改测试以检查单元边界的顶部/底部是否在视口的垂直范围内,但忽略单元的左/右部分。最简单的方法是将矩形的左侧和宽度设置为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); 
} 

这个解决方案至少让我走上了正确的道路,以下是对我有效的方法:JViewport viewport=scrollPane1.getViewport();矩形rect=myTable.getCellRect(rowToSelect,1,true);如果(!viewport.contains(rect.getLocation()))myTable.scrollRowToVisible(rowToSelect)。谢谢