Java JTable Column Size Calculate initColumnSizes(JTable table, int rowStart, int rowEnd)

Here you can find the source of initColumnSizes(JTable table, int rowStart, int rowEnd)

Description

Sets the width of the table columns to fit in the table data.

License

Open Source License

Declaration

public static void initColumnSizes(JTable table, int rowStart, int rowEnd) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import javax.swing.*;

import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import java.awt.*;

public class Main {
    /**//from   w  ww  . j  a  va2 s. co m
     * Sets the width of the table columns to fit in the table data.
     * It takes into account preffered width of the columns and data in row within given range.
     */
    public static void initColumnSizes(JTable table, int rowStart, int rowEnd) {
        boolean containsData = table.getRowCount() > 0;
        Component cellRendererComponent;
        int headerWidth;
        int cellWidth;
        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

        for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) {
            TableColumn column = table.getColumnModel().getColumn(columnIndex);

            cellRendererComponent = headerRenderer.getTableCellRendererComponent(table, column.getHeaderValue(),
                    false, false, 0, 0);
            headerWidth = cellRendererComponent.getPreferredSize().width;

            cellWidth = 0;
            if (containsData) {
                for (int row = rowStart; row < rowEnd; row++) {
                    try {
                        TableCellRenderer tableCellRenderer = table.getCellRenderer(row, columnIndex);
                        cellRendererComponent = tableCellRenderer.getTableCellRendererComponent(table,
                                table.getValueAt(row, columnIndex), false, false, row, columnIndex);
                        cellWidth = Math.max(cellWidth, cellRendererComponent.getPreferredSize().width);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }
            }

            int width = Math.max(headerWidth, cellWidth) + 7;
            column.setPreferredWidth(width);
            column.setWidth(width);
        }
    }
}

Related

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