mapp_301092 mapp_301092 - 1 month ago 8
Java Question

Copying JPanel contents to another JPanel without removing contents of original JPanel

I am new to Java swing coding. I am trying to copy JPanel contents to a new JPanel which uses contents of original JPanel to show. Also, the original JPanel contents are changing as records are changing. I tried the following code but it's totally useless.

public void addPanel(JPanel jp)
{
JPanel jp1=new JPanel();
int count=jp.getComponentCount()-1;
for(;i>=0;i--)
{
jp1.addComponent(jp.getComponent(i);
}
//after this I am setting bounds of jp1.
this.add(jp1);
}


This doesn't work if I want to make multiple JPanels as original JPanel changes. It overwrites the contents of new 'jp' over 'jp1' if used multiple times, say if used in a for loop.
I do not want to remove components of original JPanel. How can I do that?

Answer

Moving instances of Component is possible but coping them requires you to do it manually.

You can do this as a program by creating new instances of the origin class and then calling the setters with the values of the getters... But frankly, thats an error prone way and you'll need reflection for it which you shouldn't use unless really necessary.

What you can do is to override the standard Java Classes you use (e.G. JLabel) and in your overridden class you implement Cloneable where you set the parameters you need (text, bounds, whatever) then call your function like this:

public void addPanel(JPanel jp)
{
    JPanel jp1=new JPanel();
    int i=jp.getComponentCount()-1;
    for(;i>=0;i--)
    {
         jp1.addComponent(
              ((Component) // this casts the clone back to component. This is maybe superfluous.
               ((Cloneable)jp.getComponent(i) // You have to ensure that all components that are returned are in fact instances of Cloneable.
               ).clone()
              ));
    }
    //after this I am setting bounds of jp1.
    this.add(jp1);
}

If you go down that road, be sure to read the Documentation of Cloneable.