I am having trouble setting JTable column widths. The table is placed inside a JScrollPane. I am using getColumnModel().getColumn().setPreferredWidth() for each of the JTable columns but when displayed they are all the same size. If I include setAutoResizeMode(table.AUTO_RESIZE_OFF) I get the same results (only the table doesn't fill the frame). I have created a short program that exhibits this behavior. What am I missing?
package testTableData;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class TableData {
private ArrayList<String> col0 = new ArrayList<String>();
private ArrayList<Integer> col1 = new ArrayList<Integer>();
private ArrayList<Integer> col2 = new ArrayList<Integer>();
private TableDataModel model = new TableDataModel();
private JTable table = null;
private JScrollPane scrollPane;
TableData() {
table = new JTable(model);
table.setAutoResizeMode(table.AUTO_RESIZE_OFF);
table.setPreferredSize(new Dimension(300,300));
table.getColumnModel().getColumn(0).setPreferredWidth(200);
table.getColumnModel().getColumn(1).setPreferredWidth(50);
table.getColumnModel().getColumn(2).setPreferredWidth(50);
scrollPane = new JScrollPane(table);
}
public JScrollPane getScrollPane() { return(scrollPane); }
public void add(int index, String c0, Integer c1, Integer c2) {
col0.add(index, c0);
col1.add(index, c1);
col2.add(index, c2);
model.fireTableStructureChanged();
}
class TableDataModel extends AbstractTableModel {
private String[] columnNames = { "Col0", "Col1", "Col2" };
public String getColumnName(int col) { return columnNames[col].toString(); }
public int getRowCount() { return col0.size(); }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) {
if(col == 0)
return(col0.get(row));
else if(col == 1)
return(col1.get(row));
return(col2.get(row));
}
public boolean isCellEditable(int row, int col) { return false; }
public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); }
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableData td = new TableData();
td.add(0, "AAAAA", 0, 1);
td.add(1, "BBBBBBBBB", 10, 11);
td.add(2, "CCCCC", 20, 21);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.add(td.getScrollPane());
frame.setVisible(true);
}
});
}
}