Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.awt.Component;

import java.awt.Dimension;

import javax.swing.JTable;

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

public class Main {
    /**
     * Adjusts the widths and heights of the cells of the supplied table to fit their contents.
     */
    public static void sizeToContents(JTable table) {
        TableModel model = table.getModel();
        TableColumn column = null;
        Component comp = null;
        int ccount = table.getColumnModel().getColumnCount(), rcount = model.getRowCount(), cellHeight = 0;

        for (int cc = 0; cc < ccount; cc++) {
            int headerWidth = 0, cellWidth = 0;
            column = table.getColumnModel().getColumn(cc);
            try {
                comp = column.getHeaderRenderer().getTableCellRendererComponent(null, column.getHeaderValue(),
                        false, false, 0, 0);
                headerWidth = comp.getPreferredSize().width;
            } catch (NullPointerException e) {
                // getHeaderRenderer() this doesn't work in 1.3
            }

            for (int rr = 0; rr < rcount; rr++) {
                Object cellValue = model.getValueAt(rr, cc);
                comp = table.getDefaultRenderer(model.getColumnClass(cc)).getTableCellRendererComponent(table,
                        cellValue, false, false, 0, cc);
                Dimension psize = comp.getPreferredSize();
                cellWidth = Math.max(psize.width, cellWidth);
                cellHeight = Math.max(psize.height, cellHeight);
            }
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }

        if (cellHeight > 0) {
            table.setRowHeight(cellHeight);
        }
    }
}