Here you can find the source of adjustColumnPreferredWidths(JTable table)
public static void adjustColumnPreferredWidths(JTable table)
//package com.java2s; //License from project: LGPL import javax.swing.*; import java.awt.*; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; public class Main { public static void adjustColumnPreferredWidths(JTable table) { // strategy - get max width for cells in column and // make that the preferred width TableColumnModel columnModel = table.getColumnModel(); for (int col = 0; col < table.getColumnCount(); col++) { int maxwidth = 0; for (int row = 0; row < table.getRowCount(); row++) { TableCellRenderer rend = table.getCellRenderer(row, col); Object value = table.getValueAt(row, col); Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col); maxwidth = Math.max(comp.getPreferredSize().width, maxwidth); }//from w w w.j a va2s.c o m TableColumn column = columnModel.getColumn(col); TableCellRenderer headerRenderer = column.getHeaderRenderer(); if (headerRenderer == null) { headerRenderer = table.getTableHeader().getDefaultRenderer(); } Object headerValue = column.getHeaderValue(); Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col); maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width); column.setPreferredWidth(maxwidth); } } }