views:

523

answers:

2
table.getTableHeader().setResizingAllowed(false);
column = table.getColumn(columns[0]);
column.setWidth(25);
column = table.getColumn(columns[1]);
column.setWidth(225);
column = table.getColumn(columns[2]);
column.setWidth(50);
table.doLayout()

This refuses to set the columns to their specified widths. Any reason why?

+2  A: 

Swing ignores column widths set by you when resize mode of the JTable is not AUTO_RESIZE_OFF. Instead of using setWidth, use setPreferredWidth. The table will then use this value when the columns are laid out. If you set minimum, maximum and preferred width, it should work for all occasions, but your users cannot change column width themselves anymore. So use this with caution.

The layout process is described in great detail in the API-Docs

haffax
+1  A: 

To get this working for my table I overrode setBounds and set the preferred widths in there:

@Override
public void setBounds(int x, int y, int width, int height)
{
    super.setBounds(x, y, width, height);

    setPreferredColumnWidths(new double[] { 0.4, 0.4, 0.1, 0.1 });
}


I got the implementation of setPreferredColumnWidths from this article.

protected void setPreferredColumnWidths(double[] percentages)
{
    Dimension tableDim = getPreferredSize();

    double total = 0;

    for (int i = 0; i < getColumnModel().getColumnCount(); i++)
    {
        total += percentages[i];
    }

    for (int i = 0; i < getColumnModel().getColumnCount(); i++)
    {
        TableColumn column = getColumnModel().getColumn(i);
        column.setPreferredWidth(
             (int)(tableDim.width * (percentages[i] / total)));
    }
}
Luke Quinane