Java Swing - 了解 JViewport

Bra*_*rad 5 java swing viewport

我有一个带有 JScrollPane 的 JTable。我对scrollPane 视口有一些不明白的地方...我现在在表中选择行号1000,所以它上面的许多行在屏幕上不可见。现在,当我检查第 0 行在当前视口中是否可见时,它显示“是”。这是我的代码:

    JViewport viewport = scrollPane1.getViewport();
    Rectangle rect = table1.getCellRect( 0, 1, true ); 

    // Check if view completely contains the row 0 :
    if( viewport.contains( rect.getLocation() ) )
        System.out.println( "The current view contains row 0" );
Run Code Online (Sandbox Code Playgroud)

此代码始终返回 true,并且无论我站在哪一行,都会打印文本。我在这里错过了什么吗?

kle*_*tra 4

您正在寻找的方法是

 getVisibleRect()
Run Code Online (Sandbox Code Playgroud)

它在 JComponent 中定义,在您的上下文中使用它

 table1.getVisibleRect().contains(rect)
Run Code Online (Sandbox Code Playgroud)

编辑:刚刚意识到您可能仍在摸不着头脑 - 尽管已经给出的所有答案在技术上都是正确的:-)

基本上,这都是关于坐标系,即相对于给定原点的位置。当使用位置相关方法时,您必须了解该特定方法的坐标系,并且不能混合不同的系统(至少不能在不翻译一个或另一个的情况下)。

但你做了混合:

      // cellRect is in table coordinates
      Rectangle cellRect = table.getCellRect(...)
      // WRONG!!! use table coordinates in parent sytem
      table.getParent().contains(cellRect.getLocation());
Run Code Online (Sandbox Code Playgroud)

解决方案是找到一个坐标系,其中上面找到的单元格位置有意义(或者手动将单元格位置转换到父系统中,但这里不需要),有一些方法可以进行转换:

      // returns the visible part of any component in its own coordinates
      // available for all components
      Rectangle visible = table.getVisibleRect();
      // special service method in JViewport, returning the visible portion
      // of its single child in the coordinates of the child
      Rectangle viewRect = ((Viewport) (table.getParent()).getViewRect();
      // both are the same 
      visible.equals(viewRect)
Run Code Online (Sandbox Code Playgroud)

查询表本身(而不是查询其父表)是更好的选择,因为它不需要任何有关其父表的知识。