Java JTable setting Column Width

后端 未结 9 1597
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 09:57

I have a JTable in which I set the column size as follows:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredW         


        
9条回答
  •  时光说笑
    2020-12-02 10:40

    Use this method

    public static void setColumnWidths(JTable table, int... widths) {
        TableColumnModel columnModel = table.getColumnModel();
        for (int i = 0; i < widths.length; i++) {
            if (i < columnModel.getColumnCount()) {
                columnModel.getColumn(i).setMaxWidth(widths[i]);
            }
            else break;
        }
    }
    

    Or extend the JTable class:

    public class Table extends JTable {
        public void setColumnWidths(int... widths) {
            for (int i = 0; i < widths.length; i++) {
                if (i < columnModel.getColumnCount()) {
                    columnModel.getColumn(i).setMaxWidth(widths[i]);
                }
                else break;
            }
        }
    }
    

    And then

    table.setColumnWidths(30, 150, 100, 100);
    

提交回复
热议问题