Java JTable Column Width Set fitColumnWidths(TableModel model, JTable mainTable)

Here you can find the source of fitColumnWidths(TableModel model, JTable mainTable)

Description

Sets preferred column widths for the table based on header and data content.

License

Open Source License

Declaration

public static void fitColumnWidths(TableModel model, JTable mainTable) 

Method Source Code


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

import java.awt.Component;

import javax.swing.JTable;
import javax.swing.table.*;

public class Main {
    public static final int MARGIN = 4;

    /** Sets preferred column widths for the table based on header and data content. */
    public static void fitColumnWidths(TableModel model, JTable mainTable) {
        for (int col = 0; col < model.getColumnCount(); col++) {
            TableColumn tc = mainTable.getColumnModel().getColumn(col);
            TableCellRenderer tcr = mainTable.getTableHeader().getDefaultRenderer();
            int width = tcr.getTableCellRendererComponent(mainTable, model.getColumnName(col), false, false, 0, col)
                    .getPreferredSize().width + MARGIN;
            if (model.getRowCount() > 0)
                tcr = mainTable.getDefaultRenderer(model.getColumnClass(col));
            for (int row = 0; row < model.getRowCount(); row++) {
                Component c = tcr.getTableCellRendererComponent(mainTable, model.getValueAt(row, col), false, false,
                        row, col);/*from   w  w w . j  ava2 s  . c om*/
                if (width < c.getPreferredSize().width + MARGIN)
                    width = c.getPreferredSize().width + MARGIN;
            }
            tc.setPreferredWidth(width);
        }
    }
}

Related

  1. autoResizeColWidthNoFill(JTable table)
  2. calcColumnWidth(int col)
  3. chooseGoodColumnWidths(JTable table)
  4. fitColumnWidth(JTable table, int colIndex, int padding)
  5. fitColumnWidths(JTable table, int padding)
  6. getPreferredWidthForColumn(TableColumn col, JTable table)
  7. getPreferredWidthOfCell(JTable table, int rowIndex, int colIndex)
  8. getRenderedWidth(JTable table, int tableColumn, String value)
  9. getTotalColumnWidth(JTable table)