JTable Last Row Scrolling Issue

Hi,

I have a table wherein every time I add a new row it will automatically scroll to the last row. But if i add a row with a bigger height, the last row is not totally shown. Please see my code below.

privatevoid scrollToLast(JTable table)

{

int lastRow = table.getRowCount() - 1;

Rectangle rec = table.getCellRect(lastRow, 0,true);

table.scrollRectToVisible(rec);

}

I have also tried getting the vertical scrollbar and setting the maximum value but it still doesn't work.

Do you have any idea how to scroll to the very end such that the last row will be seen totally?

Thanks.

[831 byte] By [GideonRaya] at [2007-11-27 6:57:17]
# 1

I have already solved my problem. Here's mysolution and I don't know why.

private void scrollToLast(JTable table)

{

SwingUtilities.invokeLater(new Runnable()

{

public void run()

{

int lastRow = table.getRowCount() - 1;

Rectangle rec = table.getCellRect(lastRow, 0, true);

table.scrollRectToVisible(rec);

}

});

}

Can anyone explain to me why this solution solves the problem?

GideonRaya at 2007-7-12 18:34:31 > top of Java-index,Desktop,Core GUI APIs...
# 2

All code in the EDT executes sequentially. So your code in your ActionListener probably looks something like this:

a) invoke some table method

b) invoke scrollRectToVisible() method

So it looks like your code executes after the table method. But the problem is that sometimes some methods may decide to use the invokeLater() method, to place some code at the end of the EDT, so the code really executes like this:

a) invoke some table method

b) invoke scrollRectToVisible() method

c) finish executing the original table method

So what happens is that the final state of the table is not yet updated by the time your code executes. Which means in your case that the exact size is not know so the scrollRectToVisible() doesn't work as expected.

So by by using the invokeLater the execution order becomes

a) invoke some table method

b) invoke scrollRectToVisible() method with invokeLater

c) finish executing the original table method

d) to the scrollRectToVisible()

I've noticed this type of behaviour mostly when dealing with scrolling.

camickra at 2007-7-12 18:34:31 > top of Java-index,Desktop,Core GUI APIs...
# 3
Thanks for the explanation. :)
GideonRaya at 2007-7-12 18:34:31 > top of Java-index,Desktop,Core GUI APIs...