Here you can find the source of fitColumnWidths(TableModel model, JTable mainTable)
public static void fitColumnWidths(TableModel model, JTable mainTable)
//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); } } }