Java JTable Column Width Set setColumnWidths(JTable table, Insets insets, boolean setMinimum, boolean setMaximum)

Here you can find the source of setColumnWidths(JTable table, Insets insets, boolean setMinimum, boolean setMaximum)

Description

set Column Widths

License

Open Source License

Declaration

public static void setColumnWidths(JTable table, Insets insets, boolean setMinimum, boolean setMaximum) 

Method Source Code


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

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class Main {
    public static void setColumnWidths(JTable table, Insets insets, boolean setMinimum, boolean setMaximum) {
        int columnCount = table.getColumnCount();
        TableColumnModel tcm = table.getColumnModel();
        int spare = (insets == null ? 0 : insets.left + insets.right);

        for (int i = 0; i < columnCount; i++) {
            int width = calculateColumnWidth(table, i);
            width += spare;//w  w w .ja va  2  s  . c om

            TableColumn column = tcm.getColumn(i);
            column.setPreferredWidth(width);
            if (setMinimum == true) {
                column.setMinWidth(width);
            }
            if (setMaximum == true) {
                column.setMaxWidth(width);
            }
        }
    }

    public static int calculateColumnWidth(JTable table, int columnIndex) {
        int width = 0; // The return value
        int rowCount = table.getRowCount();

        for (int i = 0; i < rowCount; i++) {
            TableCellRenderer renderer = table.getCellRenderer(i, columnIndex);
            Component comp = renderer.getTableCellRendererComponent(table, table.getValueAt(i, columnIndex), false,
                    false, i, columnIndex);
            int thisWidth = comp.getPreferredSize().width;
            if (thisWidth > width) {
                width = thisWidth;
            }
        }

        return width;
    }
}

Related

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