public static void adjustColumnWidths ( JTable table , int maxWidth ) { final int safety = 20 ; for ( int c = 0 ; c < table . getColumnCount ( ) ; c ++ ) { TableColumn column = table . getColumnModel ( ) . getColumn ( c ) ; TableCellRenderer headerRenderer = column . getHeaderRenderer ( ) ; if ( headerRenderer == null ) { headerRenderer = table . getTableHeader ( ) . getDefaultRenderer ( ) ; } Component headerComponent = headerRenderer . getTableCellRendererComponent ( table , column . getHeaderValue ( ) , false , false , 0 , 0 ) ; int width = headerComponent . getPreferredSize ( ) . width ; for ( int r = 0 ; r < table . getRowCount ( ) ; r ++ ) { TableCellRenderer cellRenderer = table . getCellRenderer ( r , c ) ; Component cellComponent = cellRenderer . getTableCellRendererComponent ( table , table . getValueAt ( r , c ) , false , false , r , c ) ; Dimension d = cellComponent . getPreferredSize ( ) ; //System.out.println( // "Preferred is "+d.width+" for "+cellComponent); width = Math . max ( width , d . width ) ; } column . setPreferredWidth ( Math . min ( maxWidth , width + safety ) ) ; } }
Adjust the preferred widths of the columns of the given table depending on the contents of the cells and headers .