你能帮我理解这里发生了什么吗?我查阅了 Javadoc:JFrame 有 setLayout 方法。因此,出现什么共享错误对我来说是个谜。
public class View extends JFrame {
public View(){
// LayoutManager for the whole frame.
this.setLayout(new BoxLayout(this, BoxLayout.X_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 java.awt.Container.invalidate(Container.java:1583)
at java.awt.Component.invalidateIfValid(Component.java:2957)
at java.awt.Container.setLayout(Container.java:1484)
at javax.swing.JFrame.setLayout(JFrame.java:605)
at View.<init>(View.java:16)
at Init.main(Init.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
最佳答案
在 JFrame#getContentPane() 上试试这个
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.X_AXIS));
阅读更多 How to Use BoxLayout
所有组件都添加到 JFrame 的
内容 Pane 中。
阅读更多 Adding Components to the Content Pane
这是 JFrame 的图示
编辑
来自评论:
Well, not clear anyway. I analyze it like this: BoxLayout class needs to know it target. JFrame has setLayoutt method and needs to know its layout.
this.setLayout(manager)
内部调用 getContentPane().setLayout(manager);
下一行
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
转换为不正确的下一行。
this.getContentPane().setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
有关更多详细信息,请查看 Source code
关于java - JFrame 的 BoxLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24840860/