Java JTable Column Pack packColumn(JTable table, int colIndex)

Here you can find the source of packColumn(JTable table, int colIndex)

Description

Sets the preferred width of a column of a JTable specified by colIndex.

License

Apache License

Parameter

Parameter Description
table a parameter
colIndex a parameter

Declaration

public static void packColumn(JTable table, int colIndex) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.awt.Component;

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

public class Main {
    /**//from   w ww .j  a va 2  s .c  o  m
     * Sets the preferred width of a column of a JTable specified by colIndex.
     * The column will be just wide enough to show the column head and the
     * widest cell in the column (the computation is done per row, then). Margin
     * pixels are added to the left and right (resulting in an additional width
     * of 2*margin pixels).
     *
     * @param table
     * @param colIndex
     */
    public static void packColumn(JTable table, int colIndex) {
        // get column model and then column
        DefaultTableColumnModel columnModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn column = columnModel.getColumn(colIndex);
        // initialize width
        int width;
        // get width of column header
        TableCellRenderer renderer = column.getHeaderRenderer();
        // if the header is null, just get the default one from the table
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        // get the component used to draw the cell -- for the header, row and coumn: zero
        Component component = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false,
                0, 0);
        width = component.getPreferredSize().width;
        // get maximum width of column data
        // iterate through the rows
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, colIndex);
            // get the component used to draw the cell -- for the current cell: row and coumn are index r and colIndex
            component = renderer.getTableCellRendererComponent(table, table.getValueAt(r, colIndex), false, false,
                    r, colIndex);
            width = Math.max(width, component.getPreferredSize().width);
        }
        // add margin
        width += 2;
        // set the width
        column.setPreferredWidth(width);
    }
}

Related

  1. packColumn(JTable table, int colIndex)
  2. packColumn(JTable table, int vColIndex, int margin)
  3. packColumn(JTable table, int vColIndex, int margin)
  4. packColumn(JTable table, int vColIndex, int margin)