I am trying to pass the objects by using getter and setter method. It works when I use System.out.println("test: "+this.admin); but I can't get the objects when I call System.out.println("WHY YOU ARE NOT WORKING?! "+getAdmin());
Here is the output of the program:
test: entity.account.Admin@18a607c2
WHY YOU ARE NOT WORKING?! null
Admin Master panel panel page
public class AdminMasterPanel extends JPanel {
protected JFrame myFrame;
private Admin admin;
public Admin getAdmin() {
return admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
System.out.println("test: "+this.admin);
}
/**
* Create the panel.
*/
public AdminMasterPanel(JFrame mf) {
// Set the frame to the program
myFrame = mf;
setLayout(null);
setBounds(0, 0, 1280, 720);
System.out.println("WHY YOU ARE NOT WORKING?! "+getAdmin());
}
}
Calling setAdmin method from other class to set the admin objects:
AdminMasterPanel amp = new AdminMasterPanel(null);
amp.setAdmin(admin);
Because you call getAdmin()
before setAdmin()
. Your constructor does not even get a Admin
Object. So you are basically calling nothing with getAdmin()
.
What you have todo is this:
public AdminMasterPanel(JFrame mf, Admin admin) {
// Set the frame to the program
myFrame = mf;
setLayout(null);
setBounds(0, 0, 1280, 720);
this.admin = admin;
System.out.println("WHY YOU ARE NOT WORKING?! "+getAdmin());
}
Or since it seems like you want to set the admin with the object method setAdmin()
. You have to remove the Sysout
in your constructor.
where is your class constructor to initialize all the variables?
If you want to leave out the constructor, at least do this:
private Admin admin = new Admin();
The reason you get nullPointerException
is because you are trying to access a non-existing object.
Crash course on Classes & Objects:
Admin admin; //Doing this DOES NOT create an object
The above does not create any Admin object. What it does is create a reference which points to nothing (null).
You only create objects when you use the new
keyword.
new Admin(); //Create an Admin Object
Admin admin = new Admin(); //Create an Admin object and reference it with a variable named "admin".
So here is the problem.
private Admin admin;
admin is not initialized anywhere, so its default value is null. Since you have called getAdmin()
inside the constructor, it is being executed before the setAdmin(admin)
gets invoked.
So getAdmin()
returns null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.