Java JTable Column Width Set setDefaultColumnWidth(JTable table, int column)

Here you can find the source of setDefaultColumnWidth(JTable table, int column)

Description

Sets the width of the given JTable column to the width of its widest contained value.

License

Open Source License

Parameter

Parameter Description
table the JTable that contains the column
column the column index to set the width of

Declaration

public static final void setDefaultColumnWidth(JTable table, int column) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.Component;

import javax.swing.JTable;

import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class Main {
    /**//from w w  w  .ja v a2  s  . co  m
     * Sets the width of the given JTable column to the width of its
     * widest contained value.
     *
     * @param table  the JTable that contains the column
     * @param column the column index to set the width of
     */
    public static final void setDefaultColumnWidth(JTable table, int column) {

        int resizeMode = table.getAutoResizeMode();
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        TableCellRenderer renderer = table.getCellRenderer(0, column);
        int max = 0;
        TableModel tableModel = table.getModel();
        int rows = tableModel.getRowCount();
        for (int i = 0; i < rows; i++) {

            Object obj = tableModel.getValueAt(i, column);
            Component c = renderer.getTableCellRendererComponent(table, obj, true, true, i, column);
            max = Math.max(max, c.getPreferredSize().width);
        }

        TableColumnModel tcm = table.getColumnModel();
        TableColumn tc = tcm.getColumn(column);
        tc.setPreferredWidth(max + 4);

        table.setAutoResizeMode(resizeMode);
    }
}

Related

  1. setColumnWidth(JTable table, int[] colWidth)
  2. setColumnWidths(int[] preferredColWidths, int[] maxColWidths, int[] minColWidths, TableColumnModel columnModel, boolean[] columnsShowing)
  3. setColumnWidths(JTable p_Table, int[] p_ColumnWidths)
  4. setColumnWidths(JTable table, Insets insets, boolean setMinimum, boolean setMaximum)
  5. setColumnWidths(JTable table, Insets insets, boolean setMinimum, boolean setMaximum)
  6. setMaxnimumColumnWidths(final JTable table, final int... widths)
  7. setOptimalColumnWidth(final JTable table, final int col)
  8. SetPreferedColumnWIdth(JTable table, int[] widths)
  9. setPreferredColumnWidths(final JTable table, final float[] columnWeigths, final boolean includeHeader)