How can I maintain the width of columns set by user in JTable?

So, I am working with JTable, which is tied to my own custom data model. This is very functional, but the problem is that anytime I make changes to the table (firing tableDataChanged, tableStructureChanged, etc.), all reset column widths by themselves have default values. As far as I understand, this is due to the default assignment TableColumnModel. Outside of this reset, I am satisfied with the functionality DefaultTableColumnModel, but I would just like to keep the width of the columns if the user needs to resize them (by dragging the edge of the column header).

I know setPreferredWidth()for TableColumns, and I was able to do this successfully; I believe my question is what event should I listen to in order to preserve and set this preferred width. I tried adding PropertyChangeListenerto the table title, but I would get StackOverflow anytime I tried to resize (I assume it works recursively). I completely agree with adding an additional data element to the data model for column widths and storing it there, but I just don't know when / how to set these widths so that they are not overridden by a character fireTableStructureChanged(), etc. events. Thoughts?

+5
source share
2 answers

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);
    }

}
+1
source

What about

table.setAutoCreateColumnsFromModel(false);

, !

+1

All Articles