BoxLayout for a JFrame

核能气质少年 提交于 2020-07-03 09:22:57

问题


Could you help me understand what is going on here. I consulted Javadoc: JFrame has setLayout method. So, what sharing error springs out is a mystery to me.

public class View extends JFrame {
    public View(){

        // LayoutManager for the whole frame.
        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    }
}

Result

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)

回答1:


Try this one on JFrame#getContentPane()

this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.X_AXIS));

Read more How to Use BoxLayout


All the components are added in JFrame's content pane.

Read more Adding Components to the Content Pane

Here is the pictorial representation how JFrame looks like

enter image description here


EDIT

From comments:

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) internally calls getContentPane().setLayout(manager);

The below line

this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

is converted to below line that is not correct.

this.getContentPane().setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

For more detail have a look at Source code



来源:https://stackoverflow.com/questions/24840860/boxlayout-for-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!