0

I was trying the following code on 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);
    }
}

But I am getting the following error:

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)

and Start: Applet not initialized in the Applet Viewer.

I tried the same code on another PC on which it worked fine without any error. Is this any type of bug or an error?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MrShadow
  • 171
  • 3
  • 16
  • Where is `Product` instantiated? Line 35 wouldn't happen to be the line inside the `for` loop, would it? – Paul Jul 02 '14 at 14:03
  • Yes it is the Line number 35. – MrShadow Jul 02 '14 at 14:17
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Jul 04 '14 at 11:02

1 Answers1

1

You need to instantiate the Choice before adding items to it.

@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);
}

I don't know why the same code would work on another PC other than it wasn't the same code. No matter where you run it, you still need to instantiate the Choice first.

Paul
  • 19,704
  • 14
  • 78
  • 96