Fixed Column Table
Posted by Rob Camick on November 5, 2008
A JTable is usually displayed in a JScrollPane. This allows the table to scroll vertically or horizontally as required. Horizontal scrolling causes all columns in the table to be scrolled. In some cases you may want to prevent the leading column(s) in the table from scrolling.
JTable does not support this functionality but in combination with a JScrollPane we can achieve the desired functionality. The FixedColumnTable class is used as a convenience class to manipulate the table and scroll pane. Behind the scenes your main table is split into two. The second table will display the fixed columns and is added to the scroll panes row header. This fixed table will share the TableModel and SelectionModel with the main table.
You will create the FixedColumnTable once a TableModel has been added to your main table and the main table has been added to a scroll pane. The result will be a scroll pane that contains two tables, only one of which can be scrolled horizontally. The following code was used to create the scroll pane pictured in the image below:
JTable table = new JTable(20, 10);
JScrollPane scrollPane= new JScrollPane( table );
FixedColumnTable fct = new FixedColumnTable(2, scrollPane);
You can access the fixed table that was created by using the getFixedTable() method. This will allow you to adjust the properties of the table if required.
You can change the model of the main table and the change will be reflected in the fixed table. However, you cannot change the structure of the model.