Swing JTable: Event when row is visible, or when s

2019-04-28 12:46发布

问题:

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?

回答1:

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.