0

I've created my own CategoryComboBox from JComboBox and using an update() method to add the items. I can't understand why it's working from one String [] (see below, commented out,"Bird", "Cat", etc) and not another (transactions.getCategoriesArray() which returns also String [])

Below is my custom JComboBox:

public class CategoryComboBox extends JComboBox<String> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Transactions transactions;

    public CategoryComboBox(Transactions transactions) {
        update();
    }

    public void update() {
        removeAllItems();
//      String[] categories = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; // works
        String[] categories = transactions.getCategoriesArray(); // line 24, errors
        for( String c : categories ) {
            addItem(c);
        }
    }
}

If it helps, here is my method of the transactions object's class:

public class Transactions {

    //...

    public String [] getCategoriesArray() {
        String[] categories = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
        return categories;
    }   
}

When I click Run... in Eclipse I get the following errors in the console:

Exception in thread "main" java.lang.NullPointerException
    at biz.martyn.budget.CategoryComboBox.update(CategoryComboBox.java:24)
    at biz.martyn.budget.CategoryComboBox.<init>(CategoryComboBox.java:17)
    at biz.martyn.budget.NewTransactionDialog.<init>(NewTransactionDialog.java:36)
    at biz.martyn.budget.TransactionsToolbar.<init>(TransactionsToolbar.java:34)
    at biz.martyn.budget.Budget.main(Budget.java:41)

Should there be anything different in either case?

ntalbs
  • 28,700
  • 8
  • 66
  • 83
Martyn
  • 6,031
  • 12
  • 55
  • 121

1 Answers1

0

Not sure, but I think you should add a line to initialize your transactions filed you the constructor. The NullPointerException thrown because you didn't initialize the field.

public CategoryComboBox(Transactions transactions) {
    this.transactions = transactions;
    update();
}
ntalbs
  • 28,700
  • 8
  • 66
  • 83