How do I display a panel with a Singleton class in two different frames at a time?

I'm trying to display a singleton obj on two different Jframes, but it only shows up in the Jframe where the object is finally added (in the example Frame2). The other Jframe is empty. This Singleton class inherits from Panel and contains a label in it. Can someone please tell me how can I display this singleton object in two different frames?

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() 
{
public void run() {
 NewJFrame inst = new NewJFrame();
 inst.setTitle("Frame1");
 inst.setSize(300, 300);
 inst.setLocationRelativeTo(null);
 inst.setVisible(true);
 singltonpanel _sin = singltonpanel.instance();
 inst.add(_sin);
 inst.repaint();
 JFrame frame = new JFrame("Frame2");
 frame.setSize(300, 300);
 frame.setVisible(true);
 singltonpanel _sin1 = singltonpanel.instance();
 frame.add(_sin1);
 frame.repaint();
}
});

      

+2


a source to share


1 answer


A Swing component is only allowed to have one parent. You cannot add a component to two containers.

From http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html

Each GUI component can only be contained once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.



In other words, Swing requires your components to be arranged in a tree-like hierarchy.

Solution: You basically need to split your singleton class into model class and view class. (Check out the MVC pattern at http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller ) Then create some model views.

+7


a source







All Articles