簡體   English   中英

如何一次在兩個不同的幀中顯示Singleton類的面板?

[英]How to display panel which is of Singleton class in two different frames at a time?

我試圖在兩個不同的Jframe上顯示單例obj,但僅在最后添加了對象的Jframe中顯示它(在示例Frame2中)。 其他Jframe為空。 該Singleton類繼承自Panel,並在其中包含標簽。 有人可以告訴我如何在兩個不同的框架中顯示此單例對象嗎?

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();
}
});

一個Swing組件只允許有一個單親。 您不能將組件添加到兩個容器中。

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

每個GUI組件只能包含一次。 如果某個組件已經在容器中,並且您嘗試將其添加到另一個容器中,則該組件將從第一個容器中刪除,然后添加到第二個容器中。

換句話說,Swing要求您的組件按樹層次結構排列。

解決方案:基本上,您需要將單例類分解為模型類和視圖類。 (在http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller上檢查MVC模式),然后實例化模型的多個視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM