Here you can find the source of autoResizeColWidthNoFill(JTable table)
public static int autoResizeColWidthNoFill(JTable table)
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); you may import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.*; public class Main { public static int autoResizeColWidthNoFill(JTable table) { int totalWidth = 0; int headerWidth = 0; table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); int margin = 5; for (int i = 0; i < table.getColumnCount(); i++) { int vColIndex = i; 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(); }//from w w w . ja v a 2 s. c o m Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; headerWidth = 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; width = Math.max(width, headerWidth + 20); // Make sure the width is wider than the // header plus 20 to leave room for sorting // arrows. // Set the width col.setPreferredWidth(width); totalWidth += width; } ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()) .setHorizontalAlignment(SwingConstants.LEFT); // table.setAutoCreateRowSorter(true); table.getTableHeader().setReorderingAllowed(false); return totalWidth; } }