java - JFrame 的 BoxLayout

标签 java swing layout-manager checkboxlist

你能帮我理解这里发生了什么吗?我查阅了 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 的图示

enter image description here


编辑

来自评论:

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/

相关文章:

Java - 在 .jar 中使用 .txt 文件时出错

java - 如何知道mac平台是macOSx64还是macOSaarch64

java - 如何在我的 ListView 适配器中缓存自定义 View ?

java - KeyListener 无法与 JFrame Canvas 一起使用

java - 无法向 Jtree 添加叶子

java - 动态 JPanel 错误

java - 使用 LayoutManager 面板不显示在 JFrame 中

java - Spark数据集获取与整数列标题相同的数据

java - 火烈鸟丝带: Java. lang.IllegalArgumentException : No interpolator found for java. lang.Float :java. lang.Float

java - 自定义布局 Swing 应用程序