可能重复:
请帮我整理一下这个java.awt.BoxLayout可以';不能共享或NullPointerException
Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
at javax.swing.BoxLayout.checkContainer(BoxLayout.java:445)
at javax.swing.BoxLayout.invalidLayout(BoxLayout.java:229)
at javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:262)
at javax.awt.Container.addImpl(JFrame.java: 1068)
at java.awt.Container.add(Container.java: 935)
at javax.swing.JFrame.addImpl(JFrame.java: 545)
at java.awt.Container.add(Container.java: 352)
at BoxExample.launchFrame(BoxExample.java:26)
at BoxExample.main(BoxExample.java:40)
编辑了我自己之前发表的帖子后的代码名为:"请帮我解决这个java.awt.BoxLayout无法共享或NullPointerException"
如果你也是这篇文章的新手,请查看代码并为我解决:
//Boxlayout
import java.awt.*;
import javax.swing.*;
public class BoxExample
{
public JFrame f;
public JButton b1, b2,b3,b4,b5;
public BoxExample()
{
f=new JFrame("Box example");
f.setTitle("Box Layout Example");
f.setSize(150, 150);
b1=new JButton("Button 1");
b2=new JButton("Button 2");
b3=new JButton("Button 3");
b4=new JButton("Button 4");
b5=new JButton("Button 5");
}
public void launchFrame()
{
System.out.println("inside lf");
f.setLayout(new BoxLayout(f,BoxLayout.Y_AXIS));
System.out.println("after layset");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
BoxExample guiWindow=new BoxExample();
System.out.println("main");
guiWindow.launchFrame();
}
}
BoxLayout
无法共享,因为按钮被添加到框架的内容窗格中,但布局是以框架为目标初始化的,因此存在冲突。要修复,请替换此:
f.setLayout(new BoxLayout(f,BoxLayout.Y_AXIS));
带有:
f.setLayout(new BoxLayout(f.getContentPane(),BoxLayout.Y_AXIS));