I have an existing Jtable with data in it. I would like to create a new column with custom data in and add it to the table. I can create a new column as TableColumn tc = new TableColumn(); and add it to the table as table.addColumn(tc). But I couldn't figure out a way to set the values of the cells in the new column. Is it possible to manually set the values of the cells after I created a table column?
1 Answer
I can create a new column...
First you need to specify which column in the TableModel this TableColumn represents. For example:
tableColumn tc = new TableColumn(3)
table.addColumn(tc):
Is it possible to manually set the values of the cells after I created a table column?
Then you can use:
table.setValueAt("hello", 0, 3);
to set the value in the first row.
The easiest way to do this is the use the addColumn(...) method of the DefaultTableModel. It allows you to add an empty column or column with data.
4 Comments
MadProgrammer
That assumes that the model implementation provides the capability to store values against the model...
Brkk
table.setValueAt doesn't work for me. I'm using a custom table model, could that be the reason?Brkk
My model had its own set value at which did the trick. Thanks.
camickr
My model had its own set value at which did the trick - you should be able to use either the JTable.setValueAt(..) or TableModel.setValueAt(..) method. The table.setValueAt(...) method just invokes the TableModel.setValueAt(...) method. So you must have implemented the setValueAt(..) method incorrectly. You may want to double check this to see what the problem is.
TableModelyou are using. If it's aDefaultTableModelit's very easy, you can simply add a new column to theDefaultTableModeland usesetValueAtto update the values. If it's not you will probably need to use a "proxy"TableModelwhich wraps the original model, but also provides functionality to manage the new column(s) as well