Here you can find the source of initColumnSizes(JTable table)
public static void initColumnSizes(JTable table)
//package com.java2s; /**//from ww w .j a v a 2s. com * Copyright 2004-2005 Sun Microsystems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import javax.swing.*; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import java.awt.Component; public class Main { public static void initColumnSizes(JTable table) { TableModel model = (TableModel) table.getModel(); Object[] longValues = new Object[model.getColumnCount()]; for (int i = 0; i < model.getColumnCount(); i++) { longValues[i] = table.getModel().getColumnName(i); } TableColumn column = null; Component comp = null; int headerWidth = 0; int cellWidth = 0; TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0); headerWidth = comp.getPreferredSize().width; comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i); cellWidth = comp.getPreferredSize().width; column.setPreferredWidth(Math.max(headerWidth, cellWidth)); } } }