到目前为止,我知道如何使用JScrollPane的JViewPort对象获取特定行。
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
JViewport viewport = scrollPane.getViewport();
Point p = viewport.getViewPosition();
int rowIndex = getLogsTable().rowAtPoint(p);
System.out.println("Minimum Y: " + viewport.getViewRect().getMinY());
System.out.println("Min row: " + getLogsTable().rowAtPoint(new Point(0, (int) viewport.getViewRect().getMinY())));
System.out.println("Maximum Y: " + viewport.getViewRect().getMaxY());
System.out.println("Max row: " + getLogsTable().rowAtPoint(new Point(0, (int) viewport.getViewRect().getMaxY())));
}
});
我很难弄清楚如何获取JViewport.getMinimumY()和JViewport.getMaximumY()之间的所有行。有没有办法收集这两个视口点之间的所有行项,还是有办法只获取JScrollPane视图中的所有行?
答案 0 :(得分:1)
基于@ dic19的评论,我使用了这段代码,它起作用了。我刚刚添加了一个额外的变量来处理检索最后一行索引号。
// need to wait for table to fully load
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// getLogsTable() returns JTable instance
Rectangle vr = getLogsTable().getVisibleRect();
int firstRow = getLogsTable().rowAtPoint(vr.getLocation());
vr.translate(0, vr.height);
int visibleRows = getLogsTable().rowAtPoint(vr.getLocation()) - firstRow;
int lastRow = (visibleRows > 0) ? visibleRows+firstRow : getLogsTable().getRowCount();
System.out.println("first visible row: " + firstRow + " last visible row: " + lastRow);
for(int rowNum=firstRow+1; rowNum<=lastRow; rowNum++) {
// LogsModel is a AbstractTableModel instance
LogsModel model = (LogsModel) getLogsTable().getModel();
Log log = model.getData().get(getLogsTable().convertRowIndexToModel(rowNum-1));
System.out.println(log.getLocation());
}
System.out.println(lastRow);
}
});