Takes a JTable column in an existing table and makes it fixed-width. - Java Swing

Java examples for Swing:JTable Column

Description

Takes a JTable column in an existing table and makes it fixed-width.

Demo Code


//package com.java2s;

import javax.swing.*;
import javax.swing.table.*;

public class Main {
    /**//from www .  j  a v  a  2 s  .  c o  m
     * Takes a column in an existing table and makes it fixed-width.
     * Specifically, it sets the column's minimum and maximum widths to
     * its preferred width, and disables auto-resize for the table as a
     * whole.
     *
     * <p>
     *
     * Later on this should take a column array for efficiency.
     *
     * @param table JTable The table to modify
     * @param colIndex int Which column to fix
     * @return int The width of the column as it was fixed
     */

    public static int fixColumnToPreferredWidth(JTable table, int colIndex) {
        TableColumnModel tcm = table.getColumnModel();
        TableColumn col = tcm.getColumn(colIndex);
        int width = col.getPreferredWidth();

        col.setMaxWidth(width);
        col.setMinWidth(width);

        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        return width;
    }
}

Related Tutorials