Here you can find the source of packColumns(JTable table, int width)
public static void packColumns(JTable table, int width)
//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]); } } }