Here you can find the source of initColumnSizes(JTable table, boolean[] show)
public static int initColumnSizes(JTable table, boolean[] show)
//package com.java2s; //License from project: LGPL import java.awt.Component; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; public class Main { public static int initColumnSizes(JTable table, boolean[] show) { TableColumn column = null; Component comp = null;// w w w. j av a2 s.c om int cellWidth = 0; TableModel model = table.getModel(); int numCols = model.getColumnCount(); int numRows = model.getRowCount(); if (show != null && show.length != numCols) show = null; int sumColWidths = 0; for (int col = 0; col < numCols; col++) { column = table.getColumnModel().getColumn(col); if (show == null || show[col]) { TableCellRenderer defaultRenderer = getDefaultRenderer(table, column); TableCellRenderer cellRenderer = column.getCellRenderer(); if (cellRenderer == null) cellRenderer = defaultRenderer; TableCellRenderer headerRenderer = column.getHeaderRenderer(); if (headerRenderer == null) headerRenderer = defaultRenderer; // check the header width comp = headerRenderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, col); cellWidth = comp.getPreferredSize().width; // check the rendered width of the widest row for (int row = 0; row < numRows; row++) { Object o = model.getValueAt(row, col); comp = cellRenderer.getTableCellRendererComponent(table, o, false, false, row, col); cellWidth = Math.max(cellWidth, comp.getPreferredSize().width); } cellWidth += 10; // add padding sumColWidths += cellWidth; column.setPreferredWidth(cellWidth); column.setMinWidth(5); column.setMaxWidth(1000); } else { // hide column column.setMinWidth(0); column.setMaxWidth(0); column.setPreferredWidth(0); } } return sumColWidths; } /** * Return the default cell renderer for the given JTable column. */ public static TableCellRenderer getDefaultRenderer(JTable table, TableColumn column) { try { return table.getTableHeader().getDefaultRenderer(); } catch (Exception e) { throw new RuntimeException(e); } } }