Cloning a DefaultTableModel

Please help! I need to copy all the data from one DefaultTableModel object into another DefaultTabelModel object for use as a backup.Any ideas?Thanks in advance.
[189 byte] By [JacobsBa] at [2007-11-27 7:05:15]
# 1
Well, you can get the # of items from a model, and you can get the items from the model and you can add items to another model. Sounds like a job for a for loop.
bsampieria at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 2

The only problem with that is it is very inefficient. With the tableModel, I'd have to loop through the rows AND columns.This is a task that has to be done everytime the table is referenced by the user - which is quite often - and it's a big table with a lot of columns, so a loop for this would cause severe lag.

I was hoping for a good utility.

JacobsBa at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 3
ok, I assigned more points.....anyone?
JacobsBa at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 4

If you want a deep clone,

you can either clone each of the instance variables inside the object

or try cloning using serialization provided all the objects implememnt Serializable

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(baos);

oos.writeObject(this);

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

ObjectInputStream ois = new ObjectInputStream(bais);

Object deepCopy = ois.readObject();

watfora at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 5
its great
Aniruddha-Herea at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 6
I appreciate the response, but I am really only looking to copy all the values in the cells from one table to another. Thanks.
JacobsBa at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 7
That is exactly what the piece of code i gave you does. It deep clones the table model. Use this table model to create a new table.
watfora at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 8
Haven't tried it, but can't you put the same model into 2 tables?
bsampieria at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 9
I fail to see how it's any more or less efficient than serializing/deserializing the whole model. What do you think that does internally? It's a glorified loop thru the internals of the object. One way or another, you have too "loop" thru the contents.
bsampieria at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...
# 10

> Haven't tried it, but can't you put the same model

> into 2 tables?

no because i want to copy the tableModel. the table model is what contains my cell values. i want to keep a copy so that i can add and subtract rows from the tableModel, then if the user hits Cancel, use the copy to revert it.

JacobsBa at 2007-7-12 18:56:35 > top of Java-index,Desktop,Core GUI APIs...