首页 文章

Java Swing - 了解JViewport

提问于
浏览
3

我有一个带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" );

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

2 回答

  • 0

    你要找的方法是

    getVisibleRect()
    

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

    table1.getVisibleRect().contains(rect)
    

    编辑:刚才意识到你可能还在挠头 - 即使已经给出的所有答案在技术上都是正确的:-)

    基本上,它都是关于坐标系,即相对于给定原点的位置 . 使用与位置相关的方法时,您必须知道该特定方法的坐标系,并且您不能混合使用不同的系统(至少在没有翻译的情况下) .

    但混合你做了:

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

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

    // 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)
    

    查询表本身(而不是查询其父级)是可取的,因为它不需要任何关于其父级的知识 .

  • 3

    我认为包含与屏幕坐标有关,总是在(0,0),你想看

    JViewPort.getViewRect().contains(rect.getLocation());
    

    我相信 .

相关问题