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 * (originally from @class org.openstreetmap.josm.gui.preferences.SourceEditor) 020 * adjust the preferred width of column col to the maximum preferred width of the cells 021 * requires JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 022 * @param tbl table 023 * @param col column index 024 * @param maxColumnWidth maximum column width 025 */ 026 public static void adjustColumnWidth(JTable tbl, int col, int maxColumnWidth) { 027 int maxwidth = 0; 028 for (int row = 0; row < tbl.getRowCount(); row++) { 029 TableCellRenderer tcr = tbl.getCellRenderer(row, col); 030 Object val = tbl.getValueAt(row, col); 031 Component comp = tcr.getTableCellRendererComponent(tbl, val, false, false, row, col); 032 maxwidth = Math.max(comp.getPreferredSize().width, maxwidth); 033 } 034 tbl.getColumnModel().getColumn(col).setPreferredWidth(Math.min(maxwidth+10, maxColumnWidth)); 035 } 036}