Auto resize the widths of JTable's columns dynamically

前端 未结 3 450
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 03:07

I have a JTable with 3 columns:

- No. #
- Name
- PhoneNumber

I want to make specific width for each column as follows:

相关标签:
3条回答
  • 2020-12-11 03:50

    Here I found my answer: http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
    The idea is to check some rows' content length to adjust the column width.
    In the article, the author provided a full code in a downloadable java file.

    JTable table = new JTable( ... );
    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    
    for (int column = 0; column < table.getColumnCount(); column++)
    {
        TableColumn tableColumn = table.getColumnModel().getColumn(column);
        int preferredWidth = tableColumn.getMinWidth();
        int maxWidth = tableColumn.getMaxWidth();
    
        for (int row = 0; row < table.getRowCount(); row++)
        {
            TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
            Component c = table.prepareRenderer(cellRenderer, row, column);
            int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
            preferredWidth = Math.max(preferredWidth, width);
    
            //  We've exceeded the maximum width, no need to check other rows
    
            if (preferredWidth >= maxWidth)
            {
                preferredWidth = maxWidth;
                break;
            }
        }
    
        tableColumn.setPreferredWidth( preferredWidth );
    }
    
    0 讨论(0)
  • 2020-12-11 03:55

    Use the addRow(...) method of the DefaultTableModel to add data to the table dynamically.

    Update:

    To adjust the width of a visible column I think you need to use:

    tableColumn.setWidth(...);
    
    0 讨论(0)
  • 2020-12-11 04:00

    I actually run into this problem too. I've found one useful link that solved my issue. Pretty much get the specific column and set its setMinWidth and setMaxWidth to be the same(as fixed.)

    private void fixWidth(final JTable table, final int columnIndex, final int width) {
        TableColumn column = table.getColumnModel().getColumn(columnIndex);
        column.setMinWidth(width);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
    }
    

    Ref: https://forums.oracle.com/thread/1353172

    0 讨论(0)
提交回复
热议问题