Appending a Column to a JTable Component
To add a column to a JTable 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 JTable component
using a DefaultTableModel table model is to call
DefaultTableModel.addColumn(). You need only supply the name and
data for the new column and a new visible column will appear in the
table. However, this method of column creation is not suitable after
existing columns have undergone customizations or after the user has
made adjustments to the existing columns. All customizations and
adjustments are lost after the new column is added. For example, if
you've installed a special renderer on one of the columns or if the
user has moved a column, all these changes will be lost when the new
column is added. In fact, if you remove a column (but did not remove
the column data), the column will reappear after the new column is
added.
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 autoCreateColumnsFromModel property must be set to
false. This property causes the table component to rebuild all the
columns when a column is added to the table model. When set to false,
the table component will no longer add a visible column when a column
is added to the table model. This step must now be done explicitly.
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);
}
Post a comment