001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.util; 003 004import java.awt.Component; 005 006import javax.swing.JTable; 007import javax.swing.table.TableCellRenderer; 008 009/** 010 * The class that provide common JTable customization methods 011 */ 012public final class TableHelper { 013 014 private TableHelper() { 015 // Hide default constructor for utils classes 016 } 017 018 /** 019 * adjust the preferred width of column col to the maximum preferred width of the cells 020 * requires JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 021 * @param tbl table 022 * @param col column index 023 * @param maxColumnWidth maximum column width 024 */ 025 public static void adjustColumnWidth(JTable tbl, int col, int maxColumnWidth) { 026 int maxwidth = 0; 027 for (int row = 0; row < tbl.getRowCount(); row++) { 028 TableCellRenderer tcr = tbl.getCellRenderer(row, col); 029 Object val = tbl.getValueAt(row, col); 030 Component comp = tcr.getTableCellRendererComponent(tbl, val, false, false, row, col); 031 maxwidth = Math.max(comp.getPreferredSize().width, maxwidth); 032 } 033 tbl.getColumnModel().getColumn(col).setPreferredWidth(Math.min(maxwidth+10, maxColumnWidth)); 034 } 035 036 /** 037 * adjust the table's columns to fit their content best 038 * requires JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 039 * @param tbl table 040 * @since 14476 041 */ 042 public static void computeColumnsWidth(JTable tbl) { 043 for (int column = 0; column < tbl.getColumnCount(); column++) { 044 adjustColumnWidth(tbl, column, Integer.MAX_VALUE); 045 } 046 } 047}