2014-09-04 68 views
1

你好,我有這個問題。我正在嘗試創建2個面板。一個在BoxLayout中將標籤堆疊在另一個的頂部,另一個帶有TextFields的面板也與BoxLayout堆疊起來並與標籤對應。我嘗試了各種設置,並不斷收到錯誤。問題JPanel,JFrame,BoxLayout

我在JFrame的設置佈局的FlowLayout()

,並以此來設置面板的layoutManager

leftPanel = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS)); 

這是我已經沒有問題做過。現在有什麼問題?

錯誤:

Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared 
at javax.swing.BoxLayout.checkContainer(BoxLayout.java:465) 
at javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:249) 
at javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:282) 
at java.awt.Container.addImpl(Container.java:1125) 
at java.awt.Container.add(Container.java:415) 
at DataWriteExample.BuildLeftPanel(DataWriteExample.java:37) 
at DataWriteExample.<init>(DataWriteExample.java:24) 
at DataWriteExample.main(DataWriteExample.java:58) 
Java Result: 1 
+0

['公衆的BoxLayout( C ontainer target,int axis)' - >'target - 需要佈置的容器'](http://docs.oracle.com/javase/8/docs/api/javax/swing/BoxLayout.html#BoxLayout -java.awt.Container-int-) – 2014-09-04 04:34:18

回答

4

你可以試試這個:

leftPanel = new JPanel(); 
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); 

更新

問題與您的代碼是:

leftPanel = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS)); 
-------------------------------------^ 
// here `this` is not leftPanel, I believe its the JFrame instance 
// hence your getting the exception of cannot share the layout 
+0

爲什麼這個工作,但你不能將它添加到構造函數?你的方法解決了我的問題,但爲什麼?我可以發誓我以前在構造函數中使用它。 – 2014-09-04 04:39:08

+0

@Code_Help,請檢查更新 – Arvind 2014-09-04 04:44:01

+0

嘿,如果我嘗試添加作爲構造函數與leftPanel而不是這我仍然得到相同的錯誤。將它拆分到下一行可以解決問題。我應該能夠將佈局管理器添加到JPanel構造函數中嗎? – 2014-09-04 04:48:07