the_photon the_photon - 4 months ago 18
Java Question

how to clone a jtable

Sirs,

In short, my question is "how do you clone a jTable in a GUI developed in Netbeans."

In a little more detail, I have a

jTabbedPane
that consists of two tabs -
myTab1
and
myTab2
. Both tabs have a
jTable
that will display columns from a derby database. Any time the data in the database is updated, I want both
jTables
to update to reflect the new information. Essentially, the two
jTables
will show identical data in each cell, and any time a change is made to one there will be an automated change to the other.

Obviously, I could do this long-hand. Any time a subroutine (that changes the data in the database) is executed, I could have an
UpdateMyTable1()
and an
UpdateMyTable2()
routine to make the changes. However, in my case the
UpdateMyTable1()
function/method/subroutine would need to be a rather lengthy one, and
UpdateMyTable1()
would consist of almost identical code to
UpdateMyTable2()
. There would be a lot of redundant code.

In Neatbeans, is there a way to instantiate (or otherwise create) two
jTables
in such a way that they always mirror each others contents without writing the code out long-hand?

Answer

The solution is simple: don't think about "cloning" but instead simply have both JTables share table model. Something as simple as

table1.setModel(table2.getModel());

could work.

If they share models, then changes in the model will be shown equally in both JTables.