Java JTable Column Width Set adjustColumnPreferredWidths(JTable table)

Here you can find the source of adjustColumnPreferredWidths(JTable table)

Description

http://niravjavadeveloper.blogspot.com/2011/05/resize-jtable-columns.html

License

Open Source License

Declaration

public static void adjustColumnPreferredWidths(JTable table) 

Method Source Code


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

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

public class Main {
    /**//from  ww w. j  a v  a  2s .  co m
     * http://niravjavadeveloper.blogspot.com/2011/05/resize-jtable-columns.html
     */
    public static void adjustColumnPreferredWidths(JTable table) {
        // strategy - get max width for cells in column and
        // make that the preferred width
        TableColumnModel columnModel = table.getColumnModel();
        for (int col = 0; col < table.getColumnCount(); col++) {
            int maxwidth = 0;

            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);
            }

            TableColumn column = columnModel.getColumn(col);
            column.setPreferredWidth(maxwidth);
        }
    }
}

Related

  1. adjustColumnPreferredWidths(JTable table)
  2. adjustColumnWidth(JTable table, int buf)
  3. adjustColumnWidth(JTable tbl, int col, int maxColumnWidth)
  4. adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table)