//这是java的例题,在我的机器上能够正常javac编译,但是java执行就提示错误。提示的执行错误如下:
/*
Exception in thread "main" java.lang.NullPointerException
        at SwingExample.launchFrame(SwingExample.java:22)
        at SwingExample.main(SwingExample.java:31)
*/
//代码如下:import java.awt.*;
import javax.swing.*;
public class SwingExample
{
private JFrame f;
private JPanel p;
private JButton bw,bc;
private JButton bfile,bsave;
public SwingExample()
{
f=new JFrame("SwingExample");
bw=new JButton("West");
bc=new JButton("Work Space region");
bfile=new JButton("File");
bsave=new JButton("Save");
}
public void launchFrame()
{
Container c=f.getContentPane();
c.add(bw,BorderLayout.WEST);
c.add(bc,BorderLayout.CENTER);
p.add(bfile);
p.add(bsave);
c.add(p,BorderLayout.NORTH);
f.pack();
f.setVisible(true);
}
public static void main(String[] args)
{
SwingExample gui=new SwingExample();
gui.launchFrame();
}
};

解决方案 »

  1.   

    p没有new
    所以产生了空指针操作的异常
    在构造函数里加:
    p=  new JPanel();
      

  2.   

    import java.awt.*;
    import javax.swing.*;
    public class SwingExample
    {
    private JFrame f;
    private JPanel p;
    private JButton bw,bc;
    private JButton bfile,bsave;
    public SwingExample()
    {
    f=new JFrame("SwingExample");
    bw=new JButton("West");
    bc=new JButton("Work Space region");
    bfile=new JButton("File");
    bsave=new JButton("Save");
    p=new JPanel(); // 加上这一行
    }
    public void launchFrame()
    {
    Container c=f.getContentPane();
    c.add(bw,BorderLayout.WEST);
    c.add(bc,BorderLayout.CENTER);
    p.add(bfile);
    p.add(bsave);
    c.add(p,BorderLayout.NORTH);
    f.pack();
    f.setVisible(true);
    }
    public static void main(String[] args)
    {
    SwingExample gui=new SwingExample();
    gui.launchFrame();
    }
    };
      

  3.   

    ---p.add(bfile);
    p没有初始化,当然会抛出空指针异常
      

  4.   

    程序在编译时通得过,并不表示在运行时不出错。
    RuntimeException就是在运行时抛出的,表示程序里还有BUG,需要改进。完成好的程序应保证尽量不抛出
    RuntimeException.
    10.常见的RuntimeException :ArithmeticException,ClassCastException,IllegalArgumentException,IndexOutOfBoundsException,NullPointerException.