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.
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 TableColumnModel
s 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 ...
Get Java Swing, 2nd Edition 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.