Sam Booty Sam Booty - 16 days ago 5
Java Question

Java GUI object becomes null after passing it to a class

I am trying to pass an object of type Warehouse between two of my GUI classes and for some reason it becomes null after passing it. Is it being garbage collected? If so how do i stop it?

This is the first class which instantiates the warehouse object and fills it with dummy data and opens a new Jframe on a button prompt which i am trying to send the data to.

public class StaffLeaveMainMenu extends javax.swing.JFrame {
private Warehouse staffList = new Warehouse();
/**
* Creates new form StaffLeaveMainMenu
*/
public StaffLeaveMainMenu() {
staffList.createTestData();
System.out.print(staffList);
initComponents();
}

private void jButtonManagerActionPerformed(java.awt.event.ActionEvent evt) {
ManagerMenu newFrame = new ManagerMenu();
newFrame.setWarehouse(staffList);
newFrame.setVisible(true);
}
}


Then this is the class it is being sent to:

public class ManagerMenu extends javax.swing.JFrame {
private Warehouse staffList;
/**
* Creates new form ManagerMenu
*/
public ManagerMenu() {
listModel = new DefaultListModel();
System.out.print(staffList);
refreshListModel();
initComponents();
}

public void setWarehouse(Warehouse objTarget) {
staffList = objTarget;
}
}

Answer

staffList is null inside ManagerMenu's constructor because you are passing it after calling the constructor.

To solve it, you have to pass it in the constructor itself, not in a setter.

public ManagerMenu(Warehouse objTarget) {
    staffList = objTarget;
    listModel = new DefaultListModel();
    System.out.print(staffList);
    refreshListModel();
    initComponents();
}