Martyn Martyn - 2 months ago 10
Java Question

Extending JComboBox, errors when building with addItem and String []

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?

Answer

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