set JTable Preferred Cell Sizes - Java Swing

Java examples for Swing:JTable Cell

Description

set JTable Preferred Cell Sizes

Demo Code


//package com.java2s;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class Main {
    public static void setPreferredCellSizes(JTable table) {
        TableModel model = table.getModel();
        TableColumnModel colModel = table.getColumnModel();

        for (int i = 0; i < model.getColumnCount(); i++) {
            TableColumn column = colModel.getColumn(i);

            int longestCell = 0;
            int highestCell = 0;

            for (int j = 0; j < model.getRowCount(); j++) {
                Object value = model.getValueAt(j, i);
                if (value == null)
                    continue;

                Component cell = table.getDefaultRenderer(
                        model.getColumnClass(i))
                        .getTableCellRendererComponent(table, value, false,
                                false, j, i);

                int width = cell.getPreferredSize().width + 10;
                int height = cell.getPreferredSize().height;

                if (width > longestCell)
                    longestCell = width;
                if (height > highestCell)
                    highestCell = height;
            }//ww  w. ja  v  a 2s.  c  om

            int preferredHeight = highestCell;
            column.setPreferredWidth(longestCell);

            TableCellRenderer headerRenderer = column.getHeaderRenderer();
            if (headerRenderer != null) {
                Component headerComp = headerRenderer
                        .getTableCellRendererComponent(table,
                                column.getHeaderValue(), false, false, 0, 0);

                int headerWidth = headerComp.getPreferredSize().width;
                int headerHeight = headerComp.getPreferredSize().height;

                column.setPreferredWidth(Math.max(headerWidth, longestCell));

                preferredHeight = Math.max(headerHeight, highestCell);
            }

            int currentHeight = table.getRowHeight();

            table.setRowHeight(Math.max(currentHeight, preferredHeight));
        }
    }
}

Related Tutorials