JTable scroll to row issue

user7183233

I have the following method :

public void scrollToVisibleInstructionBlock(JTable table, int rowIndex, int sizeOfBlock) {
    if (!(table.getParent() instanceof JViewport))
        return;
    JViewport viewport = (JViewport) table.getParent();
    Rectangle rect = table.getCellRect(rowIndex, 0, true);
    Point pt = viewport.getViewPosition();
    rect.setLocation(rect.x - pt.x, rect.y - pt.y);
    viewport.scrollRectToVisible(rect);
    table.setRowSelectionInterval(rowIndex, rowIndex + sizeOfBlock - 1);
}

The functionality is nice but not optimal. I input the row to scroll to, it selects sizOfBlock rows and brings them into perception.

The problem is that the rows are always visible at the bottom of the table. For example:

enter image description here

As you can see, the selected row is at the bottom of the table. How could I perhaps bring the selected row to the top or middle?

Thanks

camickr
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, 0, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
viewport.scrollRectToVisible(rect);

I always use scrollRectTovisible(...) on the component you want to scroll:

Rectangle rect = table.getCellRect(rowIndex, 0, true);
table.scrollRectToVisible(rect);

If the row is below the current viewport position then you will be scrolled to the bottom.

If the row is above the current viewport position then you will be scrolled to the top.

If the rectangle is in the current viewport then no scrolling is done.

Doesn't really help solve your problem, just explains how scrollRectToVisible() works.

You can affect scrolling by increasing the "visible Rectangle" size. For example:

Rectangle rect = table.getCellRect(rowIndex, 0, true);
rect.height = rect.height + (table.getRowHeight() * 4);
table.scrollRectToVisible(rect);

Now the selected row should be 4 lines from the bottom when scrolling down. Doesn't really help when scrolling up as the selected row will be at the top.

How could I perhaps bring the selected row to the middle?

To position the selected row in the middle you would want to play with the viewport position directly to calculate the middle position in the viewport for the selected row:

JViewport viewport = (JViewport) table.getParent();
Rectangle r = table.getCellRect(rowIndex, 0, true);
int extentHeight = viewport.getExtentSize().height;
int viewHeight = viewport.getViewSize().height;

int y = Math.max(0, r.y - ((extentHeight - r.height) / 2));
y = Math.min(y, viewHeight - extentHeight);

viewport.setViewPosition(new Point(0, y));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related