Java JTable Column Pack packColumn(JTable table, int vColIndex, int margin)

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

Description

pack Column

License

Open Source License

Declaration

public static void packColumn(JTable table, int vColIndex, int margin) 

Method Source Code

//package com.java2s;
//License from project: Open Source 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 {

    public static void packColumn(JTable table, int vColIndex, int margin) {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }//w w  w  . j ava 2s  . c  o  m
        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false, r,
                    vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        // Set the width
        col.setPreferredWidth(width);
    }
}

Related

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