Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BoxLayout for a JFrame

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)
like image 389
Michael Avatar asked Jan 29 '26 18:01

Michael


1 Answers

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

like image 55
Braj Avatar answered Jan 31 '26 06:01

Braj