Java JTable cannot set width of column

前提是你 提交于 2019-12-12 18:29:28

问题


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);
    }

回答1:


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.




回答2:


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);
 }


来源:https://stackoverflow.com/questions/12558291/java-jtable-cannot-set-width-of-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!