Java JTable Pack packTable(final JTable table)

Here you can find the source of packTable(final JTable table)

Description

Packs a table.
Resizes all columns to the maximum width of the values in each column.

License

Apache License

Parameter

Parameter Description
table table to be packed

Declaration

public static void packTable(final JTable table) 

Method Source Code

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

import javax.swing.JTable;

import javax.swing.table.TableColumn;

public class Main {
    /**//from  w  w w  .ja  va 2 s .c o m
     * Packs a table.<br>
     * Resizes all columns to the maximum width of the values in each column.
     * @param table table to be packed
     */
    public static void packTable(final JTable table) {
        for (int column = table.getColumnCount() - 1; column >= 0; column--) {
            int maxWidth = 70; // A minimum width for the columns
            for (int row = table.getRowCount() - 1; row >= 0; row--)
                maxWidth = Math.max(maxWidth,
                        table.getRowMargin() + table
                                .getCellRenderer(row, column).getTableCellRendererComponent(table,
                                        table.getValueAt(row, column), false, false, row, column)
                                .getPreferredSize().width);
            table.getColumnModel().getColumn(column).setPreferredWidth(maxWidth);
        }
    }

    /**
     * Packs some columns of a table.<br>
     * Resizes the specified columns to exactly the maximum width of the values in each column.
     * @param table table to be packed
     * @param columns columns to be resized
     */
    public static void packTable(final JTable table, final int[] columns) {
        for (final int column : columns) {
            int maxWidth = 10; // A minimum width for the columns
            for (int row = table.getRowCount() - 1; row >= 0; row--)
                maxWidth = Math.max(maxWidth,
                        table.getRowMargin() + table
                                .getCellRenderer(row, column).getTableCellRendererComponent(table,
                                        table.getValueAt(row, column), false, false, row, column)
                                .getPreferredSize().width);
            final TableColumn tableColumn = table.getColumnModel().getColumn(column);
            tableColumn.setMaxWidth(maxWidth);
            tableColumn.setMinWidth(maxWidth);
        }
    }
}

Related

  1. packTables(final JTable tableOne, final JTable tableTwo)