Sets the JTable column width for a specific column. - Java Swing

Java examples for Swing:JTable Column

Description

Sets the JTable column width for a specific column.

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.Iterator;

import javax.swing.JTable;

import javax.swing.table.TableColumn;

public class Main {
    /**//  w  w w. j  a v a 2  s  .c  om
     * Sets the column width for a specific column.
     * @param table The table.
     * @param column The column.
     * @param width The width.
     */
    public static void setColumnWidth(JTable table, int column, int width) {
        table.getColumnModel().getColumn(column).setPreferredWidth(width);
    }

    /**
     * Returns the table column using the column name.
     *
     * @param table The table.
     * @param columnName The column name.
     * @return The table column.
     */
    public static TableColumn getColumn(JTable table, String columnName) {
        int i = table.getColumnModel().getColumnIndex(columnName);
        return table.getColumnModel().getColumn(i);
    }

    /**
     * Returns the table column from the list of table columns.
     *
     * @param list The list of TableColumns.
     * @param columnName The column name.
     * @return the table column from the list of table columns.
     */
    public static TableColumn getColumn(ArrayList<TableColumn> list,
            String columnName) {
        Iterator<TableColumn> iterator = list.iterator();
        while (iterator.hasNext()) {
            TableColumn column = iterator.next();
            if (column.getHeaderValue().equals(columnName))
                return column;
        }
        return null;
    }

    /**
     * Returns the column index for a specific column within the table.
     * @param table The JTable.
     * @param columnName The column name.
     * @return the column index for a specific column.
     */
    public static int getColumnIndex(JTable table, String columnName) {
        for (int i = 0; i < table.getColumnCount(); ++i)
            if (table.getColumnName(i).equals(columnName))
                return i;
        return -1;
    }
}

Related Tutorials