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?
By default the width of a JTable is fixed, we can also change the width of each column by using table. getColumnModel(). getColumn(). setPreferredWidth() method of JTable class.
Right-click on the table cells. From popup menu, choose "Table Contents..". Uncheck the editable check box for the column you want to make it non-editable.
To change the width to a specific measurement, click a cell in the column that you want to resize. On the Layout tab, in the Cell Size group, click in the Table Column Width box, and then specify the options you want. To make the columns in a table automatically fit the contents, click on your table.
What about
table.setAutoCreateColumnsFromModel(false);
I had this problem as well, this worked for me!
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With