gpt4 book ai didi

java - JFrame 的 BoxLayout

转载 作者:行者123 更新时间:2023-12-01 18:36:47 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com