Harry Readinger
Harry Readinger

Reputation:

JTable Column resize isn't working

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?

Upvotes: 2

Views: 6303

Answers (3)

Martin DeMello
Martin DeMello

Reputation: 12346

I could not get this working for ages, then I finally found that I needed to set autoCreateColumnsFromModel to false.

edit: ignore this, it was a consequence of firing tableStructureChanged when i wanted tableDataChanged (see discussion below, and thanks to kleopatra for identifying the mistake)

Upvotes: 0

Luke Quinane
Luke Quinane

Reputation: 16615

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

Upvotes: 0

haffax
haffax

Reputation: 6008

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

Upvotes: 3

Related Questions