set JavaFX Table Column Widths - Java JavaFX

Java examples for JavaFX:Table

Description

set JavaFX Table Column Widths

Demo Code


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

public class Main {
    public static void setColumnWidths(JTable table, Insets insets,
            boolean setMinimum, boolean setMaximum) {
        int columnCount = table.getColumnCount();
        TableColumnModel tcm = table.getColumnModel();
        int spare = (insets == null ? 0 : insets.left + insets.right);

        for (int i = 0; i < columnCount; i++) {
            int width = calculateColumnWidth(table, i);
            width += spare;/* w w w  .  j a v  a2  s  .c  o  m*/

            TableColumn column = tcm.getColumn(i);
            column.setPreferredWidth(width);
            if (setMinimum == true) {
                column.setMinWidth(width);
            }
            if (setMaximum == true) {
                column.setMaxWidth(width);
            }
        }
    }

    public static int calculateColumnWidth(JTable table, int columnIndex) {
        int width = 0; // The return value
        int rowCount = table.getRowCount();

        for (int i = 0; i < rowCount; i++) {
            TableCellRenderer renderer = table.getCellRenderer(i,
                    columnIndex);
            Component comp = renderer.getTableCellRendererComponent(table,
                    table.getValueAt(i, columnIndex), false, false, i,
                    columnIndex);
            int thisWidth = comp.getPreferredSize().width;
            if (thisWidth > width) {
                width = thisWidth;
            }
        }

        return width;
    }
}

Related Tutorials