【发布时间】:2014-04-02 14:55:41
【问题描述】:
我的问题正如标题所说的那样。
我有一个 Tracker.class、一个 TrackerGUI.class 和一个 TrackerApp.class(JFrame 的驱动程序)。 Tracker 类在 TrackerGUI.class 中初始化为private Tracker tracker
代码本身编译正确(所以我猜这意味着没有语法错误,但是当我尝试添加一个对象时,终端弹出(我正在使用 BlueJ),并给我这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at TrackerGUI$Food.actionPerformed(TrackerGUI.java:121)
点击会引导我:
public class TrackerGUI extends JFrame {
private Tracker tracker;
double calories;
double quantity;
// more initialising of GUI elements; so all the JTextField things are initialised
// setting up the GUI code, too
public class Food implements ActionListener {
public void actionPerformed (ActionEvent ae) {
double calories = Double.parseDouble(caloriesField.getText().replaceAll(",",""));
String newFood = activityField.getText();
if(calories < 0) {
textArea.append("Calories cannot be negative. \n\n");
}
else {
tracker.addFood(newFood, calories); // this line!
textArea.append(newFood + " with " + calories + " calories added to database! \n");
}
}
}
在tracker类中,addFood的代码是这样的:
public class Tracker {
ArrayList<Food> foodBase = new ArrayList<Food>();
String foodName;
Double calories;
public void addFood(String foodName, double calories)
{
Food newFood = new Food(foodName, calories);
foodBase.add(newFood);
}
我的代码中缺少什么?注意:我必须使用ArrayList,而我不能使用List 或Map 我觉得我错过了一个for 声明,它得到foodBase.size(),但我不确定它适合哪里?
【问题讨论】:
-
您是否在 TrackerGUI 中创建了
Tracker的新实例? -
哪一行是:
TrackerGUI.java:121? -
好的,我看到你将这一行标记为评论!请检查更新的答案;-)
标签: java swing user-interface arraylist jframe