1。// 取得列幅的最大值
private int getPreferredWidthForCloumn(JTable table,int icol){
TableColumnModel tcl = table.getColumnModel();
TableColumn col = tcl.getColumn(icol);
int c = col.getModelIndex(),width = 0,maxw = 0;
for(int r=0;r <table.getRowCount();++r){
TableCellRenderer renderer = table.getCellRenderer(r,c);
Component comp = renderer.getTableCellRendererComponent(table,table.getValueAt(r,c),false,false,r,c);
width = comp.getPreferredSize().width;
maxw = width > maxw?width:maxw;
}
2。自动设定列的宽度
// 设定每列的宽度为当列的最大的宽度。
for(int i= 0; i <table.getColumnCount(); i++){
int with = this.getPreferredWidthForCloumn(table,i) + 10;
with = iniCW[i] > with ? iniCW[i] : with;
table.getColumnModel().getColumn(i).setPreferredWidth(with);
}