![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e920. Appending a Column to a JTable ComponentTo add a column to aJTable component, the component must use a table
model that supports this operation. A simple implementation of such a
table model is DefaultTableModel .
The simplest way to add a column to a This example provides a routine that will add a column without
affecting the state of the existing columns. In order for the routine
to work, the DefaultTableModel model = new DefaultTableModel(); JTable table = new JTable(model); // Add a column using the simple method model.addColumn("Col1"); // Add a column with values. // The list of values are appended to the end of the // existing rows. However, if there are more column values // than there are rows, new rows with null values are // created to accommodate the extra column values. model.addColumn("Col2", new Object[]{"v2"}); // there is now 1 row with 2 columns // Disable autoCreateColumnsFromModel table.setAutoCreateColumnsFromModel(false); // Add a column without affecting existing columns betterAddColumn(table, "Col3", new Object[]{"v3"}); // This method adds a new column to table without reconstructing // all the other columns. public void betterAddColumn(JTable table, Object headerLabel, Object[] values) { DefaultTableModel model = (DefaultTableModel)table.getModel(); TableColumn col = new TableColumn(model.getColumnCount()); // Ensure that auto-create is off if (table.getAutoCreateColumnsFromModel()) { throw new IllegalStateException(); } col.setHeaderValue(headerLabel); table.addColumn(col); model.addColumn(headerLabel.toString(), values); }
e916. Enumerating the Columns in a JTable Component 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 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. |