Java JTable Column Size Calculate initColumnSizes(JTable table)

Here you can find the source of initColumnSizes(JTable table)

Description

init Column Sizes

License

Open Source License

Declaration

public static void initColumnSizes(JTable table) 

Method Source Code

//package com.java2s;
/**//from   ww w .j  a  v  a 2s. com
 *   Copyright 2004-2005 Sun Microsystems, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.Component;

public class Main {
    public static void initColumnSizes(JTable table) {
        TableModel model = (TableModel) table.getModel();
        Object[] longValues = new Object[model.getColumnCount()];

        for (int i = 0; i < model.getColumnCount(); i++) {
            longValues[i] = table.getModel().getColumnName(i);
        }

        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;

        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);

            comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table,
                    longValues[i], false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;

            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }
}

Related

  1. calculateColumnWidth(JTable table, int columnIndex)
  2. calculateColumnWidth(JTable table, int columnIndex)
  3. calculateColumnWidth_1(JTable table, int pos)
  4. fixedColumSize(TableColumn c, int width)
  5. fixSize(TableColumn column, JTable table)
  6. initColumnSizes(JTable table, boolean[] show)
  7. initColumnSizes(JTable table, int rowStart, int rowEnd)
  8. initializeTableColumns(JTable table, int size[])
  9. pointOutsidePrefSize(JTable table, int row, int column, Point p)