0

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
  • That will depend on what type of TableModel you are using. If it's a DefaultTableModel it's very easy, you can simply add a new column to the DefaultTableModel and use setValueAt to update the values. If it's not you will probably need to use a "proxy" TableModel which wraps the original model, but also provides functionality to manage the new column(s) as well Commented Mar 23, 2015 at 21:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That assumes that the model implementation provides the capability to store values against the model...
table.setValueAt doesn't work for me. I'm using a custom table model, could that be the reason?
My model had its own set value at which did the trick. Thanks.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.