Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding Column Dynamically to JTable

 
Kriti Deewan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic