O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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 knows only 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.)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required