Java JTable Column Resize resizeColumns(JTable table)

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

Description

Resize all columns in the table to fit widest row including header.

License

Open Source License

Declaration

public static void resizeColumns(JTable table) 

Method Source Code

//package com.java2s;
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved.  This code is subject to the terms
 * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */

import java.awt.FontMetrics;

import javax.swing.JTable;

import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class Main {
    private static final int BUF = 14;
    private static final int MAX = 300;

    /** Resize all columns in the table to fit widest row including header. */
    public static void resizeColumns(JTable table) {
        if (table.getGraphics() == null) {
            return;
        }/*from w w  w  .j a v  a2 s  .  c om*/

        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        FontMetrics fm = table.getFontMetrics(renderer.getFont());

        TableColumnModel mod = table.getColumnModel();
        for (int iCol = 0; iCol < mod.getColumnCount(); iCol++) {
            TableColumn col = mod.getColumn(iCol);

            int max = col.getPreferredWidth() - BUF;

            String header = table.getModel().getColumnName(iCol);
            if (header != null) {
                max = Math.max(max, fm.stringWidth(header));
            }

            for (int iRow = 0; iRow < table.getModel().getRowCount(); iRow++) {
                Object obj = table.getModel().getValueAt(iRow, iCol);
                String str = obj == null ? "" : obj.toString();
                max = Math.max(max, fm.stringWidth(str));
            }

            col.setPreferredWidth(max + BUF);
            col.setMaxWidth(MAX);
        }
        table.revalidate();
        table.repaint();
    }
}

Related

  1. reSizeColumn(TableColumn col, int min, int preferred, int max)
  2. resizeColumnWidth(JTable table)