[英]How to reference adding objects to ArrayLists inside of objects
In JavaFX I am creating a sports tracking system. 在JavaFX中,我正在创建一个运动跟踪系统。
My Object User has many Foods and many Exercises, these are stored as ArrayLists. 我的对象用户有很多食物和很多练习,这些都存储为ArrayLists。
public class User {
private ArrayList<Food> listofFood = new ArrayList<Food>();
private ArrayList<Exercise> listofExercise = new ArrayList<Exercise>();
private String um;
public User(String u) {
this.um = u;
}
public void addNewFood(Food f) {
listofFood.add(f);
}
public void addNewExercise(Exercise ex) {
listofExercise.add(ex);
}
}
Food and exercise are similar in structure. 食物和运动的结构相似。
public class Food {
private String name;
public Food(String n) {
this.name = n;
}
public void setNameFood(String n) {
this.name = n;
}
}
In my MainApp class I create a user. 在我的MainApp类中,创建一个用户。
public class MainApp {
public User UserLoggedIn;
}
and I pass in an instance of this class using the controller. 我使用控制器传入了此类的实例。
public class MainApp {
MyController c = loader.getController();
c.setDialogStage(dialogStage);
c.setApp(this);
}
And in MyController class I set the application ... 然后在MyController类中设置应用程序...
public class MyController {
public void setApp(MainApp app) {
this.mainApp = app;
}
}
... which I then reference in MyController. ...然后我在MyController中引用。
public class MyController {
mainApp.UserLoggedIn.addNewFood((new Food(nameField.getText())));
}
This gives a Null Pointer exception 这给出了空指针异常
UserLoggedIn is never instantiated and it will therefore always be null. UserLoggedIn永远不会实例化,因此它将始终为null。 Make a default constructor for MainApp() that just creates the User object.
为MainApp()创建一个仅创建User对象的默认构造函数。 Then create a getter method called getUser() that returns the user object.
然后创建一个名为getUser()的getter方法,该方法将返回用户对象。 Also, it is Java convention to use camel case instead.
同样,使用驼峰式大小写也是Java惯例。 So, UserLoggedIn should be userLoggedIn.
因此,UserLoggedIn应该是userLoggedIn。
public class MainApp
{
private User userLoggedIn;
public MainApp()
{
userLoggedIn = new User("john doe");
}
public User getUserLoggedIn()
{
return userLoggedIn;
}
}
public class MyController
{
MainApp mainApp = new MainApp();
mainApp.getUserLoggedIn().addNewFood(new Food(//enter datum here));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.