2

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);
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ga Zhua
  • 107
  • 3
  • 14

2 Answers2

2

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.

tenorsax
  • 21,123
  • 9
  • 60
  • 107
1

I found that in addition to setting the PreferredWidth of a column, it is also helpful to set the maxWidth. Depending on what you are trying to accomplish, you may also wish to set the minWidth.

 for (int i = 0; i < Timedcolumns.length; i++) {
     mtbl.addColumn(columns[i]);
     tbl.getColumnModel().getColumn(i).setPreferredWidth(100);
     tbl.getColumnModel().getColumn(i).setMaxWidth(100);
 }
Thorn
  • 4,015
  • 4
  • 23
  • 42
  • hah, I realize that need to separate the addColumn and setWidth in different loop, then it will work – Ga Zhua Sep 24 '12 at 03:28