I have a JTable with multiple columns. I want a specific column to change. I was hoping that using setPreferredWidth, the column would be resized to the size or size of the content so that there was no truncation , and the remaining columns occupy the remaining space, but instead, all the columns, including the modified ones, share the entire table space equally; as if setPreferredWidth did nothing at all . In fact, I want to be able to set the column width and reduce it to this size without reducing the content (have I emphasized this too much?) So that all columns that have not been changed fill the remaining space. Using setMaxWidth trims the content (did I mention that I didn’t like it?) How do I resize / reduce a column without trimming it and doing absolutely nothing without it? Here is the violation code:
for (int i = 0, x = 0; i < table.getColumnModel().getColumnCount(); i++) if ((x = model.getColumnWidth(i)) > -1) table.getColumnModel().getColumn(i).setPreferredWidth(x);
The table is in the JPanel (MyListPanel - BorderLayout), which is in another JPanel (GridBagLayout) added with
new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 0, 2), 0, 0))
EDIT: this is the constructor for my subclass of JPanel:
public MyListPanel(boolean showHeader, String title, ColData...columns) { super(new BorderLayout()); model = new MyListTableModel(columns); table = new JTable(model); table.addFocusListener(this); add(table); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setTitle(title); if (showHeader) add(table.getTableHeader(), BorderLayout.NORTH); for (int i = 0, x = 0; i < table.getColumnModel().getColumnCount(); i++) if ((x = model.getColumnWidth(i)) > -1) table.getColumnModel().getColumn(i).setPreferredWidth(x); setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); }
And MyListTableModel.ColData:
public static class ColData { private int index; private String title; private int width; public ColData(int _index, String _title, int _width) { index = _index; title = _title; width = _width; } }