ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java Swing – 了解JViewport

2019-06-30 19:51:33  阅读:158  来源: 互联网

标签:java viewport swing


我有一个带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,并且无论我站在哪一行,都会打印文本.我错过了什么吗?

解决方法:

你要找的方法是

 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)

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

标签:java,viewport,swing
来源: https://codeday.me/bug/20190630/1339492.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有