下面的代码“Boxlayout 示例非常符合但在运行时抛出了以下异常:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java: 1027)
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)
请帮我解决这个问题,因为它浪费了我近 1 天的生命。
//Boxlayout example
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);
JButton b1=new JButton("Button 1");
JButton b2=new JButton("Button 2");
JButton b3=new JButton("Button 3");
JButton b4=new JButton("Button 4");
JButton 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();
}
}