Java JTable Auto Resize autoResizeTableColWidths(JTable table)

Here you can find the source of autoResizeTableColWidths(JTable table)

Description

Adjust the widths of each column of a table to match the max width of each value in the table.

License

Open Source License

Parameter

Parameter Description
table table to be resized

Declaration

public static void autoResizeTableColWidths(JTable table) 

Method Source Code


//package com.java2s;
import java.awt.Component;
import java.awt.Container;

import javax.swing.JTable;

import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main {
    /**/*from  ww  w  . ja v  a2 s  . c  o  m*/
     * Adjust the widths of each column of a table to match the max width of
     * each value in the table.
     *
     * @param table table to be resized
     */
    public static void autoResizeTableColWidths(JTable table) {

        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        int fullsize = 0;
        Container parent = table.getParent();
        if (null != parent) {
            fullsize = Math.max(parent.getPreferredSize().width, parent.getSize().width);
        }
        int sumWidths = 0;
        for (int i = 0; i < table.getColumnCount(); i++) {
            DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
            TableColumn col = colModel.getColumn(i);
            int width = 0;

            TableCellRenderer renderer = col.getHeaderRenderer();
            if (renderer == null) {
                renderer = table.getTableHeader().getDefaultRenderer();
            }
            Component headerComp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false,
                    0, i);
            width = Math.max(width, headerComp.getPreferredSize().width);
            for (int r = 0; r < table.getRowCount(); r++) {
                renderer = table.getCellRenderer(r, i);
                Object tableValue = table.getValueAt(r, i);
                if (null != tableValue) {
                    Component comp = renderer.getTableCellRendererComponent(table, tableValue, false, false, r, i);
                    width = Math.max(width, comp.getPreferredSize().width);
                }
            }
            if (i == table.getColumnCount() - 1) {
                if (width < fullsize - sumWidths) {
                    width = fullsize - sumWidths;
                }
            }
            col.setPreferredWidth(width + 2);
            sumWidths += width + 2;
        }
    }
}

Related

  1. autoResizeTable(JTable aTable, int columnPadding)
  2. autoResizeTableRowHeights(JTable table)