java.awt.AWTError: BoxLayout can't be shared [duplicate]

我只是一个虾纸丫 提交于 2019-11-29 09:27:56

When calling setLayout on a JFrame, you're actually adding the layout to the JFrame's contentPane not the JFrame itself since this method is more of a convenience method that transmits the method call to the contentPane. The BoxLayout constructor must reflect this since you can't add the BoxLayout to one container and then pass in as a parameter a different container. So change this:

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

to this:

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

Also: no need for all the this. business since this. is implied, and also there is no actual need here to extend JFrame.

edit: this code below is all that is needed to demonstrate your error and its solution:

import javax.swing.*;

public class BoxLayoutFoo extends JFrame {
   public BoxLayoutFoo() {

      // swap the comments below
      setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); // comment out this line
      //setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS)); // uncomment this line

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      pack();
      setVisible(true);
   }

   public static void main(String[] args) {
      new BoxLayoutFoo();
   }
}

You should set the BoxLayout with the contentPane of the JFrame, not the JFrame itself -

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

instead of

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

I believe this will make things more clear, just try to be more explicit about your code: this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));

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