![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e916. Enumerating the Columns in a JTable ComponentColumn information such as the name of a column and the cell renderer are kept in aTableColumn 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 Note: The number of columns in a // 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; }
e917. Setting the Width of a Column in a JTable Component e918. Setting the Column Resize Mode of a JTable Component e919. Locking the Width of a Column in a JTable Component e920. Appending a Column to a JTable Component e921. Inserting a Column in a JTable Component e922. Removing a Column from a JTable Component e923. Moving a Column in a JTable Component e924. Allowing the User to Move a Column in a JTable Component e925. Allowing the User to Resize a Column in a JTable Component
© 2002 Addison-Wesley. |