Note that there are some explanatory texts on larger screens.

plurals
  1. POTableColumn setPreferredWidth not working
    primarykey
    data
    text
    <p>I have a JTable with a number of columns. I want a particular column to resize. What I was hoping was by using setPreferredWidth, the column would resize to that size, or the size of the contents such that <strong>no truncation occurred</strong> and let the rest of the columns take the remaining space, but instead, all of the columns, including the one I resized, equally split all of the space of the table; as if setPreferredWidth did <strong>nothing at all</strong>. In effect, I want to be able to set the width of a column and have it shrink to that size <strong>without truncating content</strong> (have I stressed that too much yet?) in such a way that all columns that have not been resized fill the remaining space. Using setMaxWidth truncates content (did I mention I didn't like that?) How do I resize/shrink a column without it truncating and without it doing <strong>absolutely nothing</strong>? Here is the offending code:</p> <pre><code>for (int i = 0, x = 0; i &lt; table.getColumnModel().getColumnCount(); i++) if ((x = model.getColumnWidth(i)) &gt; -1) table.getColumnModel().getColumn(i).setPreferredWidth(x); </code></pre> <p>The table is in a JPanel (MyListPanel - BorderLayout) which is in another JPanel (GridBagLayout) added with:</p> <pre><code>new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 0, 2), 0, 0)) </code></pre> <p>EDIT: This is the constructor for my subclass of JPanel:</p> <pre><code>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 &lt; table.getColumnModel().getColumnCount(); i++) if ((x = model.getColumnWidth(i)) &gt; -1) table.getColumnModel().getColumn(i).setPreferredWidth(x); setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); } </code></pre> <p>And MyListTableModel.ColData:</p> <pre><code>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; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload