Java JTable Column Pack packColumns(JTable table, int width)

Here you can find the source of packColumns(JTable table, int width)

Description

pack Columns

License

Open Source License

Declaration

public static void packColumns(JTable table, int width) 

Method Source Code

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

import java.awt.Component;

import javax.swing.JTable;

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

public class Main {
    public static void packColumns(JTable table, int width) {
        int padding = 5;
        TableColumnModel columnModel = table.getColumnModel();
        int[] widths = new int[columnModel.getColumnCount()];
        for (int j = 0; j < table.getRowCount(); j++) {
            for (int i = 0; i < widths.length; i++) {
                TableCellRenderer renderer = table.getCellRenderer(j, i);
                Object value = table.getValueAt(j, i);
                Component component = renderer.getTableCellRendererComponent(table, value, true, true, j, i);
                widths[i] = (int) Math.max(widths[i],
                        component.getPreferredSize().getWidth() + table.getIntercellSpacing().getWidth() + padding);
            }//from  w w  w .  j a v  a 2 s .  c  om
        }

        JTableHeader header = table.getTableHeader();
        int remaining = width;
        for (int i = 0; i < widths.length; i++) {
            TableColumn column = columnModel.getColumn(i);
            TableCellRenderer renderer = column.getHeaderRenderer();
            if (renderer == null) {
                renderer = header.getDefaultRenderer();
            }
            Component component = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), true, true,
                    0, i);
            widths[i] = (int) Math.max(widths[i], component.getPreferredSize().getWidth());

            // First column gets all the extra space, if any
            if (i != 0) {
                remaining -= widths[i];
            }
        }

        widths[0] = (int) Math.max(1, remaining);

        for (int i = 0; i < widths.length; i++) {
            TableColumn column = columnModel.getColumn(i);
            header.setResizingColumn(column);
            column.setWidth(widths[i]);
        }

    }
}

Related

  1. packColumn(JTable table, int vColIndex, int margin)
  2. packColumn(JTable table, int vColIndex, int margin)
  3. packColumns(final JTable table, final int margin)
  4. packColumns(JTable table)
  5. packColumns(JTable table, int margin)
  6. packColumnsWidthFixedFirst(JTable table, int margin)