我正在寻找一种方法,当JTable滚动使得特定行变得可见时,或者当表格的底部滚动到视图中时失败。理想情况下,这应该在没有轮询的情况下完成,但是通过一些事件触发。任何想法?
答案 0 :(得分:12)
将ChangeListener
添加到滚动窗格的视口。
viewport = scrollpane.getViewport();
viewport.addChangeListener(this);
然后检查可见行(也可以很容易地扩展到列)
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
}
如果您的桌子不可排序,请忽略sorter
。