Posted By:
Shawn_Castrianni
Posted On:
Monday, March 14, 2005 11:45 AM
You want the ability to freeze columns. I have implemented that in some of my JTables. However, I implement it with a trick of putting another JTable in the left margin of the scroll pane of the main JTable. This works seamlessly and you can't tell there are really two JTables side by side. It does lead to a few issues, most of which are easily solvable. The trick is that both JTables share the same TableModel but have different TableColumnModels.
JTable mainTable = new JTable(tableModel);
//Share table model
JTable frozenTable = new JTable(tableModel);
TableColumnModel frozenTCM = frozenTable.getColumnModel();
//Empty all columns in frozen table until they are frozen
while(frozenTCM.getColumnCount > 0)
frozenTCM.removeColumn(frozenTCM.getColumn(0);
//Share selection model
frozenTable.setSelectionModel(mainTable.getSelectionModel());
//Create scrollpane for both tables
JScrollPane sp = new JScrollPane(mainTable);
//Put table for frozen columns in the left margin of scroll pane
sp.setRowHeaderView(frozenTable);
//Put frozen column headers in corner of scroll pane
sp.setCorner(JScrollPane.UPPER_LEFT_CORNER,frozenTable.getTableHeader());
To freeze a column, just get and remove the column from the mainTable's TableColumnModel and add it to the frozenTable's TableColumnModel