Enumerating the Columns in a JTable Component

Column information such as the name of a column and the cell renderer are kept in a TableColumn object. The values in a column are not kept in a TableColumn object; they are kept in a TableModel object. There is one TableColumn object for each visible column. All the TableColumn objects in a JTable are maintained by a single TableColumnModel object kept by the JTable component.

This example demonstrates how to enumerate TableColumn objects in both model order (order of creation) and view order (modifiable by the user).

Note: The number of columns in a TableModel can be greater than the number of TableColumns. The reason is that if you remove a column from a JTable (or TableColumnModel), you are only removing the visual representation of the column; the column of data still exists in the TableModel.

// Returns the visible columns in the order that they appear in the model public TableColumn[] getColumnsInModel(JTable table) { java.util.List result = new ArrayList(); Enumeration enum = table.getColumnModel().getColumns(); for (; enum.hasMoreElements(); ) { result.add((TableColumn)enum.nextElement()); } // Sort the columns based on the model index Collections.sort(result, new Comparator() { public int compare(Object a, Object b) { TableColumn c1 = (TableColumn)a; TableColumn c2 = (TableColumn)b; if (c1.getModelIndex() < c2.getModelIndex()) { return -1; } else if (c1.getModelIndex() == c2.getModelIndex()) { return 0; } else { return 1; } } }); return (TableColumn[])result.toArray(new TableColumn[result.size()]); } // Returns the columns in the order that they appear in the view public TableColumn[] getColumnsInView(JTable table) { TableColumn[] result = new TableColumn[table.getColumnCount()]; // Use an enumeration Enumeration enum = table.getColumnModel().getColumns(); for (int i=0; enum.hasMoreElements(); i++) { result[i] = (TableColumn)enum.nextElement(); } // Use a for loop for (int c=0; c<table.getColumnCount(); c++) { result[c] = table.getColumnModel().getColumn(c); } return result; } // Returns the TableColumn associated with the specified column // index in the model public TableColumn findTableColumn(JTable table, int columnModelIndex) { Enumeration enum = table.getColumnModel().getColumns(); for (; enum.hasMoreElements(); ) { TableColumn col = (TableColumn)enum.nextElement(); if (col.getModelIndex() == columnModelIndex) { return col; } } return null; }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.