Swing JTable: Event when row is visible, or when scrolled to the bottom?

风格不统一 提交于 2020-01-02 04:07:07

问题


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.



来源:https://stackoverflow.com/questions/8195959/swing-jtable-event-when-row-is-visible-or-when-scrolled-to-the-bottom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!