Swing JTable:当行可见或滚动到底部时的事件?

时间:2011-11-19 17:43:56

标签: java swing scroll jtable

我正在寻找一种方法,当JTable滚动使得特定行变得可见时,或者当表格的底部滚动到视图中时失败。理想情况下,这应该在没有轮询的情况下完成,但是通过一些事件触发。任何想法?

1 个答案:

答案 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