你好,我遇到了这个问题。我正在尝试创建2个面板。其中一个标签在BoxLayout中堆叠在一起,而另一个面板与TextFields一起堆叠起来与标签对应的BoxLayout。我尝试了各种设置并不断出错。
我将JFrame上的Layout设置为FlowLayout()
并使用它来设置面板layoutManager
leftPanel = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS));
这是我之前没有遇到过的问题。现在有什么问题?
ERROR:
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 :(得分: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