Here you can find the source of setDefaultColumnWidth(JTable table, int column)
Parameter | Description |
---|---|
table | the JTable that contains the column |
column | the column index to set the width of |
public static final void setDefaultColumnWidth(JTable table, int column)
//package com.java2s; //License from project: Open Source License import java.awt.Component; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; public class Main { /**//from w w w .ja v a2 s . co m * Sets the width of the given JTable column to the width of its * widest contained value. * * @param table the JTable that contains the column * @param column the column index to set the width of */ public static final void setDefaultColumnWidth(JTable table, int column) { int resizeMode = table.getAutoResizeMode(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableCellRenderer renderer = table.getCellRenderer(0, column); int max = 0; TableModel tableModel = table.getModel(); int rows = tableModel.getRowCount(); for (int i = 0; i < rows; i++) { Object obj = tableModel.getValueAt(i, column); Component c = renderer.getTableCellRendererComponent(table, obj, true, true, i, column); max = Math.max(max, c.getPreferredSize().width); } TableColumnModel tcm = table.getColumnModel(); TableColumn tc = tcm.getColumn(column); tc.setPreferredWidth(max + 4); table.setAutoResizeMode(resizeMode); } }