or also can automatically adjust the columan size for differnt table header and content,
public class MyTableModel extends AbstractTableModel{ Object[][] data; String[] columnNames; public MyTableModel(Object[][] tableData, String[] inColumnNames){ data = tableData; columnNames = inColumnNames; } public Object getValueAt(int row, int col){ return data[row][col]; } public Class getColumnClass(int c){ return getValueAt(0, c).getClass(); } public int getColumnCount(){ return data[0].length; } public int getRowCount(){ return data.length; } public String getColumnName(int col){ return columnNames[col]; } public boolean isCellEditable(int row, int col){ if(col == 2){ return true; }else{ return false; } } public void setValueAt(Object value, int row, int col){ data[row][col] = value; fireTableCellUpdated(row, col); } }
and use the following fuction to automatically adjust private void initColumnSizes(JTable table, MyTableModel model, Object[][] tableData){ TableColumn column = null; int headerWidth = 0; int cellWidth = 0; //resize the first columan size to feet for(int i = 0; i<1; i++){ column = table.getColumnModel().getColumn(i); String colName = tmodel.getColumnName(i); JTextField t = new JTextField(colName); headerWidth = new Double((t.getPreferredSize().getWidth())).intValue(); for(int j =0; j<tableData.length ; j++){ t = new JTextField(tableData[j][i].toString()); cellWidth = Math.max(cellWidth, t.getPreferredSize().width); } column.setPreferredWidth(Math.max(headerWidth, cellWidth)); } }
public class MyTableModel extends AbstractTableModel{
Object[][] data;
String[] columnNames;
public MyTableModel(Object[][] tableData, String[] inColumnNames){
data = tableData;
columnNames = inColumnNames;
} public Object getValueAt(int row, int col){
return data[row][col];
} public Class getColumnClass(int c){
return getValueAt(0, c).getClass();
} public int getColumnCount(){
return data[0].length;
}
public int getRowCount(){
return data.length;
}
public String getColumnName(int col){
return columnNames[col];
} public boolean isCellEditable(int row, int col){
if(col == 2){
return true;
}else{
return false;
}
}
public void setValueAt(Object value, int row, int col){
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
table.getColumn("column name").setMaxWidth(width);
table.setColumnsToFit(0); //据说是JTable的bug,必须如此调用
private void initColumnSizes(JTable table, MyTableModel model, Object[][] tableData){
TableColumn column = null;
int headerWidth = 0;
int cellWidth = 0; //resize the first columan size to feet
for(int i = 0; i<1; i++){
column = table.getColumnModel().getColumn(i);
String colName = tmodel.getColumnName(i);
JTextField t = new JTextField(colName);
headerWidth = new Double((t.getPreferredSize().getWidth())).intValue();
for(int j =0; j<tableData.length ; j++){
t = new JTextField(tableData[j][i].toString());
cellWidth = Math.max(cellWidth, t.getPreferredSize().width);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}