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 */ 023 public static void adjustColumnWidth(JTable tbl, int col, int maxColumnWidth) { 024 int maxwidth = 0; 025 for (int row=0; row<tbl.getRowCount(); row++) { 026 TableCellRenderer tcr = tbl.getCellRenderer(row, col); 027 Object val = tbl.getValueAt(row, col); 028 Component comp = tcr.getTableCellRendererComponent(tbl, val, false, false, row, col); 029 maxwidth = Math.max(comp.getPreferredSize().width, maxwidth); 030 } 031 tbl.getColumnModel().getColumn(col).setPreferredWidth(Math.min(maxwidth+10, maxColumnWidth)); 032 } 033}