Java JTable Column Size Calculate adjustColumnSizes(JTable table, int column, int margin)

Here you can find the source of adjustColumnSizes(JTable table, int column, int margin)

Description

Method sets columns width to the widest value

License

Open Source License

Parameter

Parameter Description
table a parameter
column a parameter
margin a parameter

Declaration

public static void adjustColumnSizes(JTable table, int column, int margin) 

Method Source Code

//package com.java2s;
/*/*from   w  w  w.j a v  a 2s.co  m*/
* Open-Source tuning tools
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

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 {
    /**
     * Method sets columns width to the widest value
     * @param table
     * @param column
     * @param margin
     */
    public static void adjustColumnSizes(JTable table, int column, int margin) {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(column);
        int width;
        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;
        for (int r = 0; r < table.getRowCount(); ++r) {
            renderer = table.getCellRenderer(r, column);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, column), false, false, r,
                    column);
            int currentWidth = comp.getPreferredSize().width;
            width = Math.max(width, currentWidth);
        }
        width += 2 * margin;
        col.setPreferredWidth(width);
    }
}

Related

  1. autoSizeCols(JTable table)
  2. autoSizeTableColumns(JTable table)
  3. calcColumnWidth(JTable table, int col)
  4. calcColumnWidths(final JTable table)