Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.awt.Component;

import javax.swing.JTable;

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

public class Main {
    /**
     * Auto fit the column of a table.
     * @param table the table for which to auto fit the columns.
     * @param columnIndex the index of the column to auto fit.
     * @param maxWidth the maximum width that a column can take (like Integer.MAX_WIDTH).
     */
    public static void autoFitTableColumn(JTable table, int columnIndex, int maxWidth) {
        TableModel model = table.getModel();
        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
        int rowCount = table.getRowCount();
        for (int i = columnIndex >= 0 ? columnIndex : model.getColumnCount() - 1; i >= 0; i--) {
            TableColumn column = table.getColumnModel().getColumn(i);
            int headerWidth = headerRenderer
                    .getTableCellRendererComponent(table, column.getHeaderValue(), false, false, 0, 0)
                    .getPreferredSize().width;
            int cellWidth = 0;
            for (int j = 0; j < rowCount; j++) {
                Component comp = table.getDefaultRenderer(model.getColumnClass(i))
                        .getTableCellRendererComponent(table, table.getValueAt(j, i), false, false, 0, i);
                int preferredWidth = comp.getPreferredSize().width;
                // Artificial space to look nicer.
                preferredWidth += 10;
                cellWidth = Math.max(cellWidth, preferredWidth);
            }
            // Artificial space for the sort icon.
            headerWidth += 20;
            column.setPreferredWidth(Math.min(Math.max(headerWidth, cellWidth) + table.getRowMargin(), maxWidth));
            if (columnIndex >= 0) {
                break;
            }
        }
    }
}