File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Adding Column Dynamically to JTable

Kriti Deewan

Joined: May 08, 2004
Posts: 2
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
DefaultTableModel model = (DefaultTableModel)table.getModel();
TableColumn col = new TableColumn(model.getColumnCount());
//Ensure that auto-create is off
if (table.getAutoCreateColumnsFromModel()) {
throw new IllegalStateException();
model.addColumn(headerLabel.toString(), values);
i get ArrayIndexOutOfBoundsException......
java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
at java.util.Vector.elementAt(
at javax.swing.table.DefaultTableModel.getValueAt(
at .....TableSorter.getValueAt(

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
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1141

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,
Kriti Deewan

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){
public void addColumn(Object columnName,Object[] columnData){
public void addColumn(Object columnName, Vector columnData)
//super.addColumn("New",new String[]{"One","Two","Three"});

but nothing happens
I agree. Here's the link:
subject: Adding Column Dynamically to JTable
It's not a secret anymore!