Returns the JTable column using the column name. - Java Swing

Java examples for Swing:JTable Column

Description

Returns the JTable column using the column name.

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 {
    /**/*from   w  w  w . j  ava  2  s  .c o  m*/
     * 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