So I'm working with a JTable
, which is tied to a custom data model of my own. That much is all functional, but the problem I'm having is that any time that I make a change to the table (firing tableDataChanged, tableStructureChanged, etc.) all of the column widths reset themselves to the default values. I understand from researching that this has to do with the TableColumnModel
assigned by default. Outside of this resetting, I'm happy with the functionality of the DefaultTableColumnModel
, but I would just like to retain the width of the columns if a user should resize them (by dragging the edge of the column header).
I'm aware of setPreferredWidth()
for the TableColumns, and I've been able to do that successfully; I suppose my question is what sort of event I should listen for to save and set this preferred width. I tried adding a PropertyChangeListener
to the table header, but I would get a StackOverflow any time I tried to resize (I'm assuming it was running recursively). I'm perfectly okay with adding an additional data member in the data model for the column widths, and storing it there, but I just don't know when/how to set these widths so that they aren't overridden by the fireTableStructureChanged()
, etc. events. Thoughts?
Try something like this.
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class ColumnResizer {
public static void setColumnPreferredWidth(JTable table, int column,
int preferredWidth) {
TableColumnModel columnModel = table.getColumnModel();
TableColumn tableColumn = columnModel.getColumn(column);
tableColumn.setPreferredWidth(preferredWidth);
}
}