Here you can find the source of layoutColumns(JTable p_Table, boolean p_OnlyVisibleRows)
public static void layoutColumns(JTable p_Table, boolean p_OnlyVisibleRows)
//package com.java2s; //License from project: Open Source License import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; public class Main { public static void layoutColumns(JTable p_Table, boolean p_OnlyVisibleRows) { int column = 0; TableColumn c = null;/*from ww w. j a v a 2s.c o m*/ int firstRow = p_OnlyVisibleRows ? getFirstVisibleRow(p_Table) : 0; int lastRow = p_OnlyVisibleRows ? getLastVisibleRow(p_Table) : (p_Table.getModel().getRowCount() - 1); Dimension intercellSpacing = p_Table.getIntercellSpacing(); JTableHeader tableHeader = p_Table.getTableHeader(); for (java.util.Enumeration columns = tableHeader.getColumnModel().getColumns(); columns .hasMoreElements(); column++) { c = (TableColumn) columns.nextElement(); Component component = (c.getHeaderRenderer() != null) ? c.getHeaderRenderer().getTableCellRendererComponent(p_Table, c.getHeaderValue(), false, false, -1, column) : tableHeader.getDefaultRenderer().getTableCellRendererComponent(p_Table, c.getHeaderValue(), false, false, -1, column); int width = Math.max(c.getWidth(), component.getPreferredSize().width); if (firstRow >= 0) { for (int i = firstRow, d = lastRow; i <= d; i++) { width = Math .max(width, p_Table.getCellRenderer(i, column).getTableCellRendererComponent(p_Table, p_Table.getModel().getValueAt(i, column), false, false, i, column) .getPreferredSize().width + intercellSpacing.width); } } c.setPreferredWidth(width); c.setWidth(width); } } public static int getFirstVisibleRow(JTable p_Table) { Point p = p_Table.getVisibleRect().getLocation(); return p_Table.rowAtPoint(p); } public static int getLastVisibleRow(JTable p_Table) { Point p = p_Table.getVisibleRect().getLocation(); p.y = p.y + p_Table.getVisibleRect().height - 1; int result = p_Table.rowAtPoint(p); if (result > 0) return result; // if there is no rows at this point,rowatpoint() return -1, // It means that there is not enough rows to fill the rectangle where // the table is displayed. // if this case we return getRowCount()-1 because // we are sure that the last row is visible if (p_Table.getVisibleRect().height > 0) return p_Table.getRowCount() - 1; else return -1; } }