Sets preferred JTable column widths for the table based on header and data content. - Java Swing

Java examples for Swing:JTable Column

Description

Sets preferred JTable column widths for the table based on header and data content.

Demo Code


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

import javax.swing.JTable;
import javax.swing.table.*;

public class Main {
    public static final int MARGIN = 4;

    /** Sets preferred column widths for the table based on header and data content. */
    public static void fitColumnWidths(TableModel model, JTable mainTable) {
        for (int col = 0; col < model.getColumnCount(); col++) {
            TableColumn tc = mainTable.getColumnModel().getColumn(col);
            TableCellRenderer tcr = mainTable.getTableHeader()
                    .getDefaultRenderer();
            int width = tcr.getTableCellRendererComponent(mainTable,
                    model.getColumnName(col), false, false, 0, col)
                    .getPreferredSize().width
                    + MARGIN;// w  w w. ja v  a2s .  c om
            if (model.getRowCount() > 0)
                tcr = mainTable.getDefaultRenderer(model
                        .getColumnClass(col));
            for (int row = 0; row < model.getRowCount(); row++) {
                Component c = tcr.getTableCellRendererComponent(mainTable,
                        model.getValueAt(row, col), false, false, row, col);
                if (width < c.getPreferredSize().width + MARGIN)
                    width = c.getPreferredSize().width + MARGIN;
            }
            tc.setPreferredWidth(width);
        }
    }
}

Related Tutorials