Java examples for Swing:JTable Column
Pack specified JTable column.
//package com.java2s; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; public class Main { /**/* w w w . java2s .c o m*/ * Pack specified column. Sets the preferred width of the specified visible * column so it is will be just wide enough to show the column head and the * widest cell value in the column + {@code margin} each side. * * Taken from http://www.exampledepot.com/egs/javax.swing.table/PackCol.html * * NB: If a table has more than 100 rows, then only the width of the column * header will be checked and not the widest cell value. Otherwise it could * take too long. * * @param table * table with column to pack * @param vColIndex * column to pack * @param margin * margin to leave at each side of the column (resulting in an * additional width of 2*margin pixels). */ public static void packColumn(JTable table, int vColIndex, int margin) { DefaultTableColumnModel colModel = (DefaultTableColumnModel) table .getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); int width = 0; // Get width of column header TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = table.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; // because checking the width of each row can be time consuming, // only do so if less than 101 rows. boolean checkDataWidth = (table.getRowCount() < 101); if (checkDataWidth) { // Get maximum width from all column data for (int r = 0; r < table.getRowCount(); r++) { renderer = table.getCellRenderer(r, vColIndex); comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false, r, vColIndex); width = Math.max(width, comp.getPreferredSize().width); } } // Add margin width += 2 * margin; // Set the width col.setPreferredWidth(width); } }