import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class FrozenColumnHeader extends JScrollPane {
protected JTable mainTable;
protected JTable headerTable;
protected int columnCount;
public FrozenColumnHeader(JTable table, int columns) {
super();
mainTable = table;
headerTable = new JTable(mainTable.getModel());
getViewport().setView(headerTable);
columnCount = columns;
}
public void addNotify() {
TableColumn column;
super.addNotify();
TableColumnModel mainModel = mainTable.getColumnModel();
TableColumnModel headerModel = new DefaultTableColumnModel();
int frozenWidth = 0;
for (int i = 0; i < columnCount; i++) {
column = mainModel.getColumn(0);
mainModel.removeColumn(column);
headerModel.addColumn(column);
frozenWidth += column.getPreferredWidth() + headerModel.getColumnMargin();
}
headerTable.setColumnModel(headerModel);
Component columnHeader = getColumnHeader().getView();
getColumnHeader().setView(null);
JScrollPane mainScrollPane = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, mainTable);
mainScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, new JLabel("..."));
headerTable.setPreferredScrollableViewportSize(new Dimension(frozenWidth, 0));
}
}
|