如题
------解决方案--------------------
public class TestTable {
public static void main(String[] args) {
JFrame frame = new JFrame( "表格 ");
String[] headers = { "第一列 ", "第二列是一个长列 "};
TableColumn tc1 = new TableColumn();
TableColumn tc2 = new TableColumn();
tc1.setHeaderValue(headers[0]);
tc2.setHeaderValue(headers[1]);
tc1.setWidth(headers[0].length()*20);
tc2.setWidth(headers[1].length()*20);
DefaultTableColumnModel dtc = new DefaultTableColumnModel();
dtc.addColumn(tc1);
dtc.addColumn(tc2);
JTableHeader th = new JTableHeader(dtc);
th.setLayout(new FlowLayout());
frame.getContentPane().add(th);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
------解决方案--------------------
TableCellRenderer renderer = table.getTableHeader().getDefaultRenderer();
for (int columnindex = 0, columncount = table.getColumnCount();columnindex <columncount;columnindex++) {
Component c = renderer.getTableCellRendererComponent(table, table.getColumnName(columnindex), false, false, 0, columnindex);
Dimension dim = c.getPreferredSize();
TableColumn tc = table.getColumn(table.getColumnName(columnindex));
tc.setWidth(dim.width);
tc.sizeWidthToFit();
}