0

I am trying to add this list of Strings

private String[] dest = {"New York", "Dahab", "Rome", "Sydney", "Tokyo"};

To this combo box like so

    for(int i = 0; i < dest.length; i++){
        System.out.println(dest[i]);
        destinationField.addItem(dest[i]);
    }

However I get a NullPointerException on the destinationField.addItem(dest[i]); line

JComboBox<String> destinationField;

1 Answers1

3

Probably your destinationField is getting there in a null form, because otherwise, if the problem was the dest[i] you would have a nullpointer in the line System.out.println(dest[i]);.

Try this:

JComboBox<String> destinationField = new JComboBox<>();

Your reference destinationField was not pointing to a real object in memory, so when you tried to use it inside the for, it didn't have a real object in memory. So, the new word makes it, allocate a real object to memory.

Bruno Franco
  • 1,958
  • 8
  • 20