Re: The first & last visible rows in a JTable
Wes Harrison schreef:
Is there an elegant way to work out the first and last rows of a JTable that
are visible on the screen at a particular time? All I could come up with
was to go through each point on the screen and do a getRowAtPoint() and work
it out from that. Is there a better or simpler way?
Thanks,
Wes
I'm not really sure I understand what you really want, but following
code wil give you the first and last row in a table:
import javax.swing.*;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
public class TableTest extends JPanel {
private TableTest() {
setLayout(new BorderLayout());
final JTable table = new JTable(new TestTableModel());
JScrollPane scroller = new JScrollPane(table);
add(scroller);
scroller.getViewport().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JViewport viewport = (JViewport) e.getSource();
Rectangle viewRect = viewport.getViewRect();
System.out.println("First = " + table.rowAtPoint(new
Point(0, viewRect.y)));
System.out.println("Last = " + table.rowAtPoint(new
Point(0, viewRect.y + viewRect.height - 1)));
System.out.println("=-=-=-=-=-=-=");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel panel = new TableTest();
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
private static class TestTableModel extends AbstractTableModel {
public int getColumnCount() {
return 3;
}
public int getRowCount() {
return 100;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return rowIndex + "-" + columnIndex;
}
}
}
Regards,
Bart