2013-11-26 147 views
4

我有一個包含一堆上下文的JPanel。將JPanel添加到多個JFrame中

我希望能夠將上述JPanel添加到兩個JFrames。有小費嗎?

這就是例子我想

public class Test 
{ 
    public static void main(String [] args) 
    { 
     JPanel panel = new JPanel(); 
     panel.add(new JLabel("Hello world")); 
     panel.validate(); 

     JFrame frame1, frame2; 
     frame1 = new JFrame("One"); 
     frame2 = new JFrame("Two"); 
     frame1.add(panel); 
     frame2.add(panel); 
     frame1.validate(); 
     frame2.validate(); 
     frame1.setVisible(true); 
     frame2.setVisible(true); 
     frame1.pack(); 
     frame2.pack(); 
    } 
} 

我希望兩個JFrames顯示的hello world,而不是一個展示它,另一個是空的。如果JPanel更新中的數據我想要兩個JFrames來顯示它。

感謝任何人的幫助,這一直在困擾着我一段時間。

回答

6

我不認爲你可以。當您爲其添加Component時,java.awt.Container中的代碼包含此珍聞。在這裏,讀JFrameContainer和你JPanelcomp

 /* Reparent the component and tidy up the tree's state. */ 
     if (comp.parent != null) { 
      comp.parent.remove(comp); 
      if (index > component.size()) { 
       throw new IllegalArgumentException("illegal component position"); 
      } 
     } 

(這是在java.awt.Container.addImpl(Component, Object, int)

於是就在那裏,當你將它添加到一個不同的Container,從舊的Container刪除。我想你可以重寫這個基礎級別的AWT代碼,但我不會推薦它。

+0

謝謝:)我是非常有希望的,這是可能的,但我想不會:( – Quillion

1

所有Swing組件只能有一個家長,這意味着如果你添加組件到另一個容器中,將自動從第一容器中取出......

試着像...

JPanel panel = new JPanel(); 
    panel.add(new JLabel("Hello world")); 

    JFrame frame1, frame2; 
    frame1 = new JFrame("One"); 
    frame1.add(panel); 
    frame1.pack(); 
    frame1.setVisible(true); 

    JPanel panel2 = new JPanel(); 
    panel2.add(new JLabel("Hello world")); 
    frame2 = new JFrame("Two"); 
    frame2.add(panel2); 
    frame2.pack(); 
    frame2.setVisible(true); 

相反

1

聽起來像你想的一樣的東西兩個視圖,因爲它沒有一個JPanels在兩幀的工作,你有沒有考慮建立每兩個面板與您要視圖這件事參考在每個面板的規定這個問題?

粗略的想法在下面草繪。實質上,你不需要兩個獨立的JPanel來反映彼此,你需要兩個反映別的東西的JPanel。

class Data<T> { 
.....stuff 
    void update(); 
    T getdata(); 
} 

class DataView<T> extends JPanel { 
    private Data<T> data; 
    ...stuff 
    public DataView(T data) { 
    this.data = data; 
    } 
    ...stuff 
    protected void paintComponent(Graphics g) { 
    drawData(); 
    ...stuff 
    } 
} 

然後

public static void main(String[] args) { 
    Data<String> data = new Data(); 
    DataView<String> dataViewOne = new DataView(data); 
    DataView<String> dataViewTwo = new DataView(data); 
    ..add to two seperate frames, pack set visible etc.. 
}