Table Column Manager
Posted by Rob Camick on May 8, 2011
When using a JTable the user has some control over the view of the columns in the table. The columns can be resized and they can be reordered. One feature that is not supported is the ability to hide and reshow a column.
Hiding a column is easy. You can just remove the TableColumn from the TableColumnModel. The problem is reshowing the column. When you remove the column from the model you also lose all the information about the column. Information like:
- the text of the column. This is the heading that appears in the table header for the column
- the last known width of the column
- the last know position of the column in the view of the table
The solution to these problems is to use the TableColumnManager. The TableColumnManager will handle hide and show requests and then invoke the appropriate TableColumnModel method. Using this approach the manager is able to keep track of the necessary column information. Users have full control over the visibility of a column by using the popup menu that is installed on the table header. Right clicking on any column of the table header will show the popup containing all the columns managed by the TableColumnManager.
The code to add a TableColumnManager to the table shown in the image above was:
JTable table = new JTable( new DefaultTableModel(15, 10) );
TableColumnManager tcm = new TableColumnManager(table);
Hopefully this will give the users a little more flexibility when using tables.