I'm looking for a way to be informed when a JTable has scrolled such that a particular row becomes visible, or failing that, when the bottom of the table has scrolled into view. Ideally this should be done without polling, but through some event firing. any ideas?
Asked
Active
Viewed 2,222 times
6
-
Check this link: http://www.exampledepot.com/egs/javax.swing.table/IsVis.html - and this: http://www.exampledepot.com/egs/javax.swing/scroll_SpEvt.html – Eng.Fouad Nov 19 '11 at 17:48
-
thanks, altho that seems like i'd have to poll. On further thought perhaps i could insert a cell renderer, that when it renderers fires the event that says it's visible. I'm going to try that. – MeBigFatGuy Nov 19 '11 at 17:52
-
no, not a task for a renderer - it's supposed to be completely passive. And it may be called at any time, before/after the table is visible (f.i. when sizing rows/columns) – kleopatra Nov 19 '11 at 18:43
-
@MeBigFatGuy please see my question http://stackoverflow.com/questions/8197261/jtable-how-to-change-background-color – mKorbel Nov 19 '11 at 20:56
-
forgot my usual question: why? – kleopatra Nov 20 '11 at 11:31
-
1why? i'm doing paging. when you scroll down to the bottom, i want to load more. – MeBigFatGuy Nov 21 '11 at 17:43
-
thanks for satisfying my curiousity :-) – kleopatra Nov 22 '11 at 09:06
1 Answers
13
Add a ChangeListener
to the viewport of the scrollpane.
viewport = scrollpane.getViewport();
viewport.addChangeListener(this);
then this checks the visible rows (can easily be extended to columns as well)
public void stateChanged(ChangeEvent e)
{
Rectangle viewRect = viewport.getViewRect();
int first = table.rowAtPoint(new Point(0, viewRect.y));
if (first == -1)
{
return; // Table is empty
}
int last = table.rowAtPoint(new Point(0, viewRect.y + viewRect.height - 1));
if (last == -1)
{
last = tableModel.getRowCount() - 1; // Handle empty space below last row
}
for (int i = first; i <= last; i++)
{
int row = sorter.convertRowIndexToModel(i); // or: row = i
//... Do stuff with each visible row
}
if (last == tableModel.getRowCount() - 1) {} //... Last row is visible
}
Ignore the sorter
if your table is not sortable.

Mark Jeronimus
- 9,278
- 3
- 37
- 50