adjust JTable Column Preferred Widths - Java Swing

Java examples for Swing:JTable Column

Description

adjust JTable Column Preferred Widths

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 {

    public static void adjustColumnPreferredWidths(JTable table) {
        // ?Component?preferredSize
        TableColumnModel columnModel = table.getColumnModel();
        for (int col = 0; col < table.getColumnCount(); col++) {
            int maxwidth = 0;
            TableCellRenderer rend = table.getCellRenderer(10000, 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/*from  w  w w .  j  a  v  a 2 s  . c o  m*/
                        .max(comp.getPreferredSize().width, maxwidth);
            } // for row

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

            // 2.rendererComponent
            Object headerValue = column.getHeaderValue();
            Component headerComp = headerRenderer
                    .getTableCellRendererComponent(table, headerValue,
                            false, false, 0, col);

            // 3.
            maxwidth = Math.max(maxwidth,
                    headerComp.getPreferredSize().width);

            // 4.
            column.setPreferredWidth(maxwidth);
        } // for col
    }
}

Related Tutorials