I try to set width for the columns, but it didn't work at all, I have been searching for answers for hours, and here is my code, can anyone tell me what is the problem. Thanks in advance.
String [] columns = {"Day","StratTime","EndTime","Description"};
mtbl = new DefaultTableModel();
tbl = new JTable(mtbl);
jsPane = new JScrollPane(tbl);
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < Timedcolumns.length; i++) {
mtbl.addColumn(columns[i]);
tbl.getColumnModel().getColumn(i).setPreferredWidth(100);
}
解决方案
As a result of addColumn(), JTable may end up rebuilding all the columns. Here is a snippet from JTable.tableChanged() :
public void tableChanged(TableModelEvent e) {
if (e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW) {
...
if (getAutoCreateColumnsFromModel()) {
// This will effect invalidation of the JTable and JTableHeader.
createDefaultColumnsFromModel();
return;
}
...
TableModelEvent.HEADER_ROW is fired as a result of addColumn() execution by DefaultTableModel. addColumn executes fireTableStructureChanged:
public void fireTableStructureChanged() {
fireTableChanged(new TableModelEvent(this, TableModelEvent.HEADER_ROW));
}
You end up setting preferred size only on the last column that was added, as the rest of the columns were recreated by createDefaultColumnsFromModel().
All in all, it is probably simpler to set preferred sizes after all the columns were created in a separate loop.