Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 742
Brad Avatar asked Oct 12 '22 08:10

Brad


1 Answers

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.

like image 106
kleopatra Avatar answered Oct 14 '22 04:10

kleopatra