views:

732

answers:

2
//can set column widths using percentages   
private void setPreferredTableColumnWidths(JTable table, double[] percentages) 
{
 Dimension tableDim = table.getSize(); 

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

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

I want to be able to change the widths of a JTable based on a percentage of the total width of the table. The above code looks like it should work, but I only get equal width columns when I call it using "setPreferredTableColumnWidths(table, new double[] {.01,.4,.2,.2,.2});"

What could be the problem?

A: 

Try to add the line:

table.doLayout();

At the end of the method.

Maurice Perry
+1  A: 

Your code works fine but depending on where you call it the table may or may not have a width. In the constructor of a Panel (or whatever contains the table) there is not width yet.

I put the call to your method in the paint() method. But be sure to keep track and only call it once or it will resize the columns over and over.

@Override
public void paint(Graphics g) {
 super.paint(g);

 if(! this.initialSizeSet){
  this.setPreferredTableColumnWidths(this.table, new double[] {0.1, 0.1, 0.5, 0.3});
  this.initialSizeSet = true;
 }
}
Tim Bornholtz