Here you can find the source of initColumnSizes(JTable table, int rowStart, int rowEnd)
public static void initColumnSizes(JTable table, int rowStart, int rowEnd)
//package com.java2s; //License from project: Open Source License import javax.swing.*; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.*; public class Main { /**//from w ww . j a va2 s. co m * Sets the width of the table columns to fit in the table data. * It takes into account preffered width of the columns and data in row within given range. */ public static void initColumnSizes(JTable table, int rowStart, int rowEnd) { boolean containsData = table.getRowCount() > 0; Component cellRendererComponent; int headerWidth; int cellWidth; TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) { TableColumn column = table.getColumnModel().getColumn(columnIndex); cellRendererComponent = headerRenderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, 0, 0); headerWidth = cellRendererComponent.getPreferredSize().width; cellWidth = 0; if (containsData) { for (int row = rowStart; row < rowEnd; row++) { try { TableCellRenderer tableCellRenderer = table.getCellRenderer(row, columnIndex); cellRendererComponent = tableCellRenderer.getTableCellRendererComponent(table, table.getValueAt(row, columnIndex), false, false, row, columnIndex); cellWidth = Math.max(cellWidth, cellRendererComponent.getPreferredSize().width); } catch (Exception ex) { ex.printStackTrace(); } } } int width = Math.max(headerWidth, cellWidth) + 7; column.setPreferredWidth(width); column.setWidth(width); } } }