Auto resizing the JTable column widths

后端 未结 4 845
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 05:13

I need my JTable to automatically re-size its column widths to fit the content. I found the TableColumnAdjuster class very useful. But there\'s a small problem. Say i have 5

相关标签:
4条回答
  • 2020-11-27 05:48

    You can try the next:

    public void resizeColumnWidth(JTable table) {
        final TableColumnModel columnModel = table.getColumnModel();
        for (int column = 0; column < table.getColumnCount(); column++) {
            int width = 15; // Min width
            for (int row = 0; row < table.getRowCount(); row++) {
                TableCellRenderer renderer = table.getCellRenderer(row, column);
                Component comp = table.prepareRenderer(renderer, row, column);
                width = Math.max(comp.getPreferredSize().width +1 , width);
            }
            if(width > 300)
                width=300;
            columnModel.getColumn(column).setPreferredWidth(width);
        }
    }
    

    JTable

    This needs to be executed before the resize method.
    If you have:

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    

    JTable

    0 讨论(0)
  • 2020-11-27 05:56

    There is no option to automatically resize one column larger than the other.

    Maybe you can to something like:

    tca = new TableColumnAdjuster( table, 0 );
    tca.adjustColumns();
    TableColumnModel tcm = table.getColumnModel();  
    TableColumn tc = tcm.getColumn(1);
    tc.setWidth(tc.getWidth() + 25);
    

    This would allow you to add extra space to column 1. This extra space would only be added the first time the table is displayed.

    Another option is to use:

    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    

    This would allocate extra space proportionally to each column.

    0 讨论(0)
  • 2020-11-27 06:05

    setAutoResizeMode() will tell your table how to resize you should give it a try will all different options available to see the differences, in My case I wanted to specifically resize two columns and let it decide how to adjust all the other ones.

    jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
    TableColumnModel colModel=jTable1.getColumnModel();
    colModel.getColumn(1).setPreferredWidth(25);    
    colModel.getColumn(2).setPreferredWidth(400);
    
    0 讨论(0)
  • 2020-11-27 06:05

    You can do this:

    JPanel jp = new JPanel();
    jp.add(table);
    
    jp.setLayout(new GridLayout(1,1)); /* little trick ;) and believe me that this step is important to the automatic all columns resize! A import is also needed for using GridLayout*/
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); // this is obvius part
    
    0 讨论(0)
提交回复
热议问题