adjust JTable Column Width By Header - Java Swing

Java examples for Swing:JTable Column

Description

adjust JTable Column Width By Header

Demo Code


//package com.java2s;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main {
    static public void adjustColWidthByHeader(JTable l_Table) {
        int i, width;
        TableColumn l_Col;/*from   w  w  w  .j  av a 2s  . c om*/

        for (i = 0; i < l_Table.getColumnCount(); i++) {
            l_Col = l_Table.getColumn(l_Table.getColumnName(i));
            width = columnHeaderWidth(l_Table, l_Col) + 6;

            l_Col.setMinWidth(width);
            l_Col.setMaxWidth(width);

        }
    }

    static private int columnHeaderWidth(JTable l_Table, TableColumn col) {
        TableCellRenderer renderer = l_Table.getTableHeader()
                .getDefaultRenderer();

        Component comp = renderer.getTableCellRendererComponent(l_Table,
                col.getHeaderValue(), false, false, 0, 0);
        return comp.getPreferredSize().width;
    }
}

Related Tutorials