2014-01-29 40 views
0

下面的代碼用於佈局組件返回錯誤的Java的BoxLayout返回錯誤的BoxLayout不能共享

public class MainPanel extends JPanel 
{ 
    private JTextField txt1, txt2; 
    private JButton btnCopy, btnCut, btnDel; 
    private JPanel wrapper1, wrapper2; 

    public MainPanel() 
    { 
     txt1 = new JTextField(); 
     txt2 = new JTextField(); 

     btnCopy = new JButton("Copy"); 
     btnCut = new JButton("Cut"); 
     btnDel = new JButton("Delete"); 

     wrapper1 = new JPanel(); 
     wrapper1.setLayout(new BoxLayout(wrapper1, BoxLayout.Y_AXIS)); 
     wrapper1.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 
     wrapper1.add(txt1); 
     wrapper1.add(txt2); 

     wrapper2 = new JPanel(); 
     wrapper2.setLayout(new BoxLayout(wrapper1, BoxLayout.Y_AXIS)); 
     wrapper2.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 
     wrapper2.add(btnCopy); 
     wrapper2.add(btnCut); 
     wrapper2.add(btnDel); 

     setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); 
     add(wrapper1); 
     add(wrapper2); 
    } 
} 

我知道類似的問題的BoxLayout can't be shared error 但它並沒有解決我的問題,因爲我不使用的JFrame但代替的JPanel

錯誤:

Exception in thread "AWT-EventQueue-0" java.awt.AWTError: BoxLayout can't be shared 
at javax.swing.BoxLayout.checkContainer(BoxLayout.java:464) 
at javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:248) 
at javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:281) 
at java.awt.Container.addImpl(Container.java:1120) 
at java.awt.Container.add(Container.java:410) 
at copycut.MainPanel.<init>(MainPanel.java:39) 
at copycut.CopyCut.<init>(CopyCut.java:23) 
at copycut.CopyCut$1.run(CopyCut.java:39) 
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) 
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) 
at java.awt.EventQueue.access$200(EventQueue.java:103) 
at java.awt.EventQueue$3.run(EventQueue.java:688) 
at java.awt.EventQueue$3.run(EventQueue.java:686) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) 
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) 
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 
+0

添加堆棧跟蹤,以便我們儘快爲您提供幫助! – Aarav

+0

還要考慮'javax.swing.Box',「一個使用'BoxLayout'對象作爲佈局管理器的輕量級容器。」 – trashgod

回答

1

我相信不是:

wrapper2.setLayout(new BoxLayout(wrapper1, BoxLayout.Y_AXIS)); 

你想做的事:

wrapper2.setLayout(new BoxLayout(wrapper2, BoxLayout.Y_AXIS)); 

現在,您可以創建一個新的BoxLayoutwrapper1父並使其成爲wrapper2佈局嘗試「共享」了。這只是一個錯誤的模式(或者在快速複製/粘貼後最可能的一些遺漏):p