Reputation: 19215
I'm using a JTable
to display data. When a row is selected programmatically, it should (automatically) scroll that row into view so that it is the first row on top. For this I have the following method:
private static void scrollToSelectedRow(JTable table)
{
JViewport viewport = (JViewport) table.getParent();
Rectangle cellRectangle = table.getCellRect(table.getSelectedRow(), 0, true);
Rectangle visibleRectangle = viewport.getVisibleRect();
table.scrollRectToVisible(new Rectangle(cellRectangle.x, cellRectangle.y, (int) visibleRectangle.getWidth(), (int) visibleRectangle.getHeight()));
}
The problem is that calling this may or may not scroll correctly, e.g. the selected row may be on top or not in a non-deterministic way. In order to fix this, I tried calling the method twice with a delay in-between as well as repainting it:
public static void setSelectedRow(JTable table, int rowIndex, int columnIndex)
{
table.setRowSelectionInterval(rowIndex, columnIndex);
scrollToSelectedRow(table);
try
{
Thread.sleep(100);
} catch (InterruptedException exception)
{
exception.printStackTrace();
}
scrollToSelectedRow(table);
table.repaint();
}
This works a lot better but still sometimes glitches the table columns out since apparently it is not smart to halt the EDT
while it is updating. The repaint()
call appears to prevent the rows from "overlapping" in a similar fashion. The graphical glitches can be fixed easily by moving the mouse over the affected rows/columns though but it should not happen.
How can I gracefully perform the scrolling without waiting and without having graphical glitches?
Upvotes: 1
Views: 1534
Reputation: 324137
Code looks reasonable. Normally the trick is to make sure the Rectangle width/height is the size of the viewport to force the scroll.
Two thoughts.
Get rid of the Thread.sleep(). all that will do is prevent the GUI from repainting itself for 100ms.
Try wrapping the scrollRectToVisible(...)
in a SwingUtlities.invokeLater(...)
.
If point 2 doesn't help then post a proper [mcve] that demonstrates the problem.
Upvotes: 3