开发者

Java Swing - Understanding the JViewport

I have a JTable with a JScrollPane. There is something i do not understand with the scrollPane viewport ... I am now selecting row number 1000 in the table, so many rows above it are not visible on the screen. Now when i check if row 0 is visible in the current viewport, it says 'Yes'. Here is my code :

    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" );

This code 开发者_运维问答always returns true, and the text is printed, whatever the row i am standing on. Am i missing something here ?


The method you'r looking for is

 getVisibleRect()

it's defined in JComponent, in your context you use it

 table1.getVisibleRect().contains(rect)

edit: just realized that you probably are still scratching your head - even though all answers already given are technically correct :-)

Basically, it's all about coordinate systems, that is a location relative to a given origin. When using location related methods, you have to be aware of the coordinate system for that particular method is and you can't mix different systems (at least not without translating the one or other).

But mixing you did:

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

The solution is to find a coordinate system where the cell location as found above makes sense (or translate the cell location into the parent system manually, but that's not needed here), there are methods which do the translation:

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

querying the table itself (as opposed to querying its parent) is preferable, because it doesn't need any knowlegde about its parent.


I believe contains relates to the on screen coordinates that are always at (0,0), You want to look at

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

i believe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜