Automatically adjust cell width of the given JTable - Java Swing

Java examples for Swing:JTable Cell

Description

Automatically adjust cell width of the given JTable

Demo Code


//package com.java2s;

import java.awt.Component;

import javax.swing.JTable;

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

public class Main {
    /**//w  w  w. j  av a2 s.  c o  m
     * Automatically adjust cell width of the given JTable
     * 
     * @param table
     */
    public static void adjustColumnPreferredWidths(JTable table) {
        // Set the preferredSize of a column to the widest cell of it
        TableColumnModel columnModel = table.getColumnModel();
        for (int col = 0; col < table.getColumnCount(); col++) {
            int maxwidth = 0;
            TableCellRenderer rend = table.getCellRenderer(
                    Integer.MAX_VALUE, col);
            for (int row = 0; row < table.getRowCount(); row++) {
                // TableCellRenderer rend = table.getCellRenderer(row, col);
                Object value = table.getValueAt(row, col);
                Component comp = rend.getTableCellRendererComponent(table,
                        value, false, false, row, col);
                maxwidth = Math
                        .max(comp.getPreferredSize().width, maxwidth);
            } // for row

            // -- then we should take column header into consideration --
            TableColumn column = columnModel.getColumn(col);
            // 1.Get the TableCellRenderer instance representing the
            // headerRenderer
            TableCellRenderer headerRenderer = column.getHeaderRenderer();
            if (headerRenderer == null)
                headerRenderer = table.getTableHeader()
                        .getDefaultRenderer();

            // 2.Get the rendererComponent by the TableCellRenderer
            // instance(a
            // DefaultTableCellHeaderRenderer in fact)
            Object headerValue = column.getHeaderValue();
            Component headerComp = headerRenderer
                    .getTableCellRendererComponent(table, headerValue,
                            false, false, 0, col);

            // 3.Compare its width with current MAX
            maxwidth = Math.max(maxwidth,
                    headerComp.getPreferredSize().width);

            // 4.OK this is the result!
            column.setPreferredWidth(maxwidth);
        } // for col
    }
}

Related Tutorials