How to display panel which is of Singleton class in two different frames at a time?
I am trying to display a singleton obj on two different Jframe, but it is displayed only in the Jframe in which the object is added at last ( in example Frame2). Other Jframe is empty. This Singleton class is inherited from Panel and contains a label in it. Can anybody please tell me how can i display开发者_高级运维 this singleton object in two different frame ?
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();
}
});
A Swing component is only allowed to have a single parent. You may not add a component to two containers.
From http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html
Each GUI component can be contained only 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-hierarchy.
Solution: You basically need to break up your singleton-class into a model class and a view class. (Check out the MVC pattern at http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) Then instantiate multiple views of the model.
精彩评论