Large Tables with Paging

Working conveniently with very large tables can be a pain. Scrolling up and down is fine as long as the table is only a few hundred lines long, but when it gets larger, a tiny movement in the scrollbar can change your position by a few thousand rows. One way to solve this is by combining paging with scrolling. We’ll create a table with 10,000 rows (large enough to make scrolling through the entire table a real hassle) and add buttons to page up and down 100 rows at a time. Within any group of 100 rows, you can use the scrollbar as usual to move around. Figure 16.2 shows the result.

A paging (and scrolling) table

Figure 16-2. A paging (and scrolling) table

In this example, we’re using a simple trick. There are really two tables to worry about: a logical table that contains all 10,000 rows, which might represent records that were read from a database, and the physical table that’s instantiated as a JTable object and displayed on the screen. To do this trick, we implement a new table model, PagingModel, which is a subclass of AbstractTableModel. This table model keeps track of the data for the entire logical table: all 10,000 rows. However, when a JTable asks it for data to display, it pretends it only knows about the 100 rows that should be on the screen at this time. It’s actually quite simple. (And we don’t even need to worry about any column models; the default column model is adequate.) ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.