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

A Table with Row Headers

As we promised, this is a table with headers for both rows and columns. The JTable handles the column headers itself; we need to add machinery for the rows. Figure 16-1 shows the resulting table. It shows column labels, plus two data columns from a larger table. Scrolling works the way you would expect. When you scroll vertically, the row headers scroll with the data. You can scroll horizontally to see other data columns, but the row headers remain on the screen.

A table with both row and column headers

Figure 16-1. A table with both row and column headers

The trick is that we really have two closely coordinated tables: one for the row headers (a table with only one column) and one for the data columns. There is a single TableModel, but separate TableColumnModels for the two parts of the larger table. In the figure, the gray column on the left is the row header; it’s really column 0 of the data model.

To understand what’s going on, it helps to remember how a Swing table models data. The TableModel itself keeps track of all the data for the table, i.e., the values that fill in the cells. There’s no reason why we can’t have two tables that share the same table model—that’s one of the advantages of the model-view-controller architecture. Likewise, there’s no reason why we can’t have data in the table model that isn’t displayed; the table model can keep track of a logical table that is much larger ...

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