get JTable Preferred Width For Column - Java Swing

Java examples for Swing:JTable Column

Description

get JTable Preferred Width For Column

Demo Code


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

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main {
    public static int getPreferredWidthForColumn(JTable table,
            TableColumn col) {//  w  w  w .  j  a va2  s .c o m
        int hw = columnHeaderWidth(table, col), // hw = header width
        cw = widestCellInColumn(table, col); // cw = column width

        return hw > cw ? hw : cw;
    }

    private static int columnHeaderWidth(JTable table, TableColumn col) {
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = new DefaultTableCellRenderer();
            ((DefaultTableCellRenderer) renderer).setText(col
                    .getHeaderValue().toString());
        }
        Component comp = renderer.getTableCellRendererComponent(table,
                col.getHeaderValue(), false, false, 0, 0);
        //System.out.println("preferered width:"+comp.getPreferredSize().width);
        return comp.getPreferredSize().width + 2;
    }

    private static int widestCellInColumn(JTable table, TableColumn col) {
        int c = col.getModelIndex(), width = 0, maxw = 0;
        for (int r = 0; r < table.getRowCount(); ++r) {
            TableCellRenderer renderer = table.getCellRenderer(r, c);
            Component comp = renderer.getTableCellRendererComponent(table,
                    table.getValueAt(r, c), false, false, r, c);
            width = comp.getPreferredSize().width + 2;
            maxw = width > maxw ? width : maxw;
        }
        return maxw;
    }
}

Related Tutorials