我已经从CategoryComboBox
创建了我自己的JComboBox
并使用update()
方法添加了这些项目。我无法理解为什么它会从一个String []
开始工作(见下文,注释掉," Bird"," Cat"等)而不是另一个(transactions.getCategoriesArray()
也返回String []
)
以下是我的自定义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);
}
}
}
如果有帮助,这是我的交易对象类的方法:
public class Transactions {
//...
public String [] getCategoriesArray() {
String[] categories = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
return categories;
}
}
当我在Eclipse中单击Run ...时,我在控制台中收到以下错误:
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)
两种情况都应该有什么不同吗?
答案 0 :(得分:0)
不确定,但我认为你应该添加一行来初始化你的transactions
提交给你的构造函数。引发NullPointerException
因为您没有初始化该字段。
public CategoryComboBox(Transactions transactions) {
this.transactions = transactions;
update();
}