Tuesday, July 21, 2009

Showing JTable Header Without Using JScrollPane

Most tutorials and examples about JTable put it within a JScrollPane. If you do not place the JTable inside a JScrollPane, the header is not automatically shown.

However, JTable does create it. To show it, simply call JTable.getTableHeader() and add it to the Container. Just as importantly, you can continue to control the columns (such as changing column width and switching columns) from the header.

For example, you can easily put the header NORTH of a BorderLayout:
setLayout(new BorderLayout());
JTable table = new JTable(data, headerLabels);
add(table.getTableHeader(), BorderLayout.NORTH);
add(table, BorderLayout.CENTER);
Note that you could conceivably put the header in the SOUTH position. However, you can only have one header showing at a time. If you add it in both the NORTH and then the SOUTH location, it will only show up in the SOUTH location.

No comments:

Post a Comment