Java examples for Swing:JTable Column
Sets preferred JTable column widths for the table based on header and data content.
//package com.java2s; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.*; public class Main { public static final int MARGIN = 4; /** Sets preferred column widths for the table based on header and data content. */ public static void fitColumnWidths(TableModel model, JTable mainTable) { for (int col = 0; col < model.getColumnCount(); col++) { TableColumn tc = mainTable.getColumnModel().getColumn(col); TableCellRenderer tcr = mainTable.getTableHeader() .getDefaultRenderer(); int width = tcr.getTableCellRendererComponent(mainTable, model.getColumnName(col), false, false, 0, col) .getPreferredSize().width + MARGIN;// w w w. ja v a2s . c om if (model.getRowCount() > 0) tcr = mainTable.getDefaultRenderer(model .getColumnClass(col)); for (int row = 0; row < model.getRowCount(); row++) { Component c = tcr.getTableCellRendererComponent(mainTable, model.getValueAt(row, col), false, false, row, col); if (width < c.getPreferredSize().width + MARGIN) width = c.getPreferredSize().width + MARGIN; } tc.setPreferredWidth(width); } } }