aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Adding Column Dynamically to JTable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Adding Column Dynamically to JTable" Watch "Adding Column Dynamically to JTable" New topic
Author

Adding Column Dynamically to JTable

Kriti Deewan
Greenhorn

Joined: May 08, 2004
Posts: 2
hi,
i am using JTable with model as DefaultTableModel,using TableSorter
and adding values into model from database.everything goes fine(Table data
display and sorting),created own TableSorter
thing is that when i am adding column dynamically using
.........code........
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);
}
.......
i get ArrayIndexOutOfBoundsException......
java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:618)
at .....TableSorter.getValueAt(TableSorter.java:248)

Intially i have four columns added by using Vector
and used where data1 is a vector of vector,c is a vector
dataModel.setDataVector(data1, c);

Hope i will get a good debugger
Kriti
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1134

Kriti,
Allow me to suggest an easier way (in my opinion): use the "addColumn()" method of class "DefaultTableModel". Here is an example. The below code will display a "JTable" and a "JButton". When you click on the "JButton", an extra column will be added to the "JTable".
[Written, compiled and tested on Windows XP with J2SE SDK 1.4.2_04]

Good Luck,
Avi.
Kriti Deewan
Greenhorn

Joined: May 08, 2004
Posts: 2
hi Avi,
thanks but it doesnot worked for me...
i am getting model of a table,i have a class that extends DefaultTableModel
in that i have written
public void addColumn(Object columnName){
super.addColumn(columnName);
}
public void addColumn(Object columnName,Object[] columnData){
}
public void addColumn(Object columnName, Vector columnData)
{
super.addColumn(columnName,columnData);
//super.addColumn("New",new String[]{"One","Two","Three"});
super.fireTableStructureChanged();
}

but nothing happens
Kriti
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Adding Column Dynamically to JTable