0

我在 NetBeans IDE 8.0 上尝试了以下代码:

public class ChoiceProgramDemo extends Applet implements ItemListener{

    Label l1 = new Label();
    Choice Product;

    @Override
    public void init() {
        String[] ProductList = new String[4];
        ProductList[0]="Pen";
        ProductList[1]="Pencil";
        ProductList[2]="Eraser";
        ProductList[3]="NoteBook";

        for(int i=0;i<ProductList.length;i++)
        {
            Product.insert(ProductList[i], i);
        }

        add(Product);
        add(l1);
        Product.addItemListener(this);
    }
    public void itemStateChanged(ItemEvent ie)
    {
        int Selection;
        Selection=Product.getSelectedIndex();
        System.out.println(Selection);
    }
}

但我收到以下错误:

java.lang.NullPointerException
    at ChoiceProgramDemo.init(ChoiceProgramDemo.java:35)
    at sun.applet.AppletPanel.run(AppletPanel.java:435)
    at java.lang.Thread.run(Thread.java:745)

Start: Applet not initialized在小程序查看器中。

我在另一台 PC 上尝试了相同的代码,它运行良好,没有任何错误。这是任何类型的错误或错误吗?

4

1 回答 1

1

您需要在向其Choice添加项目之前实例化。

@Override
public void init() {
    // you are missing this line
    Choice Product = new Choice();
    //
    String[] ProductList = new String[4];
    ProductList[0]="Pen";
    ProductList[1]="Pencil";
    ProductList[2]="Eraser";
    ProductList[3]="NoteBook";

    for(int i=0;i<ProductList.length;i++)
    {
        Product.insert(ProductList[i], i);
    }

    add(Product);
    add(l1);
    Product.addItemListener(this);
}

我不知道为什么相同的代码可以在另一台 PC 上运行,除了它不是相同的代码。无论你在哪里运行它,你仍然需要先实例化 Choice。

于 2014-07-02T14:54:24.057 回答