简体   繁体   中英

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;
}
}

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();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM