简体   繁体   English

我关闭表单然后重新打开它后,Java netbeans ArrayList重置为0

[英]Java netbeans ArrayList resetting back to 0 after i close the form then reopen it

Hi i have a main menu form and when you click customers opens a new CustomerRegistration form. 嗨,我有一个主菜单表格,当您单击客户时,将打开一个新的CustomerRegistration表格。 The customer details are filled in and then it adds a Person of type Customer. 填写客户详细信息,然后添加“客户”类型的“人员”。 (Person is an abstract class) then adds it to the arlCustomers Arraylist. (Person是一个抽象类),然后将其添加到arlCustomers Arraylist中。 This all works and the size of the list increases, but it is when i close that form using dispose() and go back to the main menu that the issue arrises as when i click back on the customer button the arlCustomers list size is back at 0 and I cant figure out why. 所有这些都有效并且列表的大小增加了,但是正是当我使用dispose()关闭该表单并返回到主菜单时,该问题才出现,因为当我单击客户按钮时,返回arlCustomers列表大小为0,我不知道为什么。 I can only think that it is creating a new list each time i call the Customer Registration form but I am stumped on how to fix it. 我只能认为,每次我致电“客户注册”表单时,它都在创建一个新列表,但我对如何解决它感到困惑。

I have tried declaring the list locally, settings the values of the list before the new CustomerRegistration window is called and moving where i declare the customerList but still no change. 我尝试在本地声明该列表,在调用新的CustomerRegistration窗口之前设置列表的值,然后将其移动到我声明了customerList的位置,但仍保持不变。

MainMenu.java MainMenu.java

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import dataModel.Consignment;
import dataModel.Customer;
import dataModel.MobileWarehouse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

/**
 *
 * @author Rich
 */
public class MainMenu extends javax.swing.JFrame {
    private ArrayList<Customer> currentCustomers = new ArrayList();
    private Customer customer = new Customer();

    /**
     * Creates new form MainMenu
     */
    public MainMenu() {  
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lblTitle = new javax.swing.JLabel();
        btnConsignments = new javax.swing.JButton();
        btnCustomers = new javax.swing.JButton();
        btnStaff = new javax.swing.JButton();
        btnReports = new javax.swing.JButton();
        Admin = new javax.swing.JButton();
        btnSettings = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Fast Courier Service");

        lblTitle.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        lblTitle.setText("Demo Couriers");

        btnConsignments.setText("Consignments");
        btnConsignments.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnConsignmentsMouseClicked(evt);
            }
        });

        btnCustomers.setText("Customers");
        btnCustomers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCustomersMouseClicked(evt);
            }
        });

        btnStaff.setText("Staff");

        btnReports.setText("Reports");

        Admin.setText("Admin");

        btnSettings.setText("Settings");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnConsignments, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblTitle)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(btnCustomers, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnStaff, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(64, 64, 64)
                                .addComponent(btnReports, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(38, 38, 38)
                                .addComponent(Admin, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(132, 132, 132)
                                .addComponent(btnSettings, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConsignments, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCustomers, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnStaff, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnReports, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Admin, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addComponent(btnSettings, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(94, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btnConsignmentsMouseClicked(java.awt.event.MouseEvent evt) {                                             
        try {
            new Consignments().setVisible(true);
        } catch (ParseException ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                            

    private void btnCustomersMouseClicked(java.awt.event.MouseEvent evt) {                                          

        try {
          **new CustomerRegistration().setVisible(true);**
        } catch (ParseException ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainMenu().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Admin;
    private javax.swing.JButton btnConsignments;
    private javax.swing.JButton btnCustomers;
    private javax.swing.JButton btnReports;
    private javax.swing.JButton btnSettings;
    private javax.swing.JButton btnStaff;
    private javax.swing.JLabel lblTitle;
    // End of variables declaration                   
}

Person.java 人.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dataModel;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Rich
 */
public abstract class Person implements Serializable {
    protected int ID = 0;
    protected String name = "Unknown";
    protected String email = "Unknown";
    protected String addressLine1 = "Unkown";
    protected String addressLine2 = "Unknown";
    protected String addressLine3 = "Unknown";
    protected String postCode = "Unknown";
    protected double costPerKg = 0.00;
    protected Role role;
    ArrayList<Customer> arlCustomers = new ArrayList<Customer>();

    public Person() {

    }

    public Person(String name) 
    {
        this.name = name;
    }

    public Person(String name, Role role, String addressLine1, String addressLine2, String addressLine3,
            String postCode) 
    {
        this.name = name;
        this.addressLine1 = addressLine1;
        this.addressLine2 = addressLine2;
        this.addressLine3 = addressLine3;
        this.postCode = postCode;

        //ID = generateID();
    }

    public Person(String name, String email, double costPerKg,  String addressLine1, String addressLine2, String addressLine3,
            String postCode) 
    {
        this.name = name;
        this.addressLine1 = addressLine1;
        this.addressLine2 = addressLine2;
        this.addressLine3 = addressLine3;
        this.postCode = postCode;
        this.costPerKg = costPerKg;

        //ID = generateID();
    }

    public void createTestData() throws ParseException
    {
        //arlCustomers = new ArrayList();

//        item = new Customer("Rich mann", "rich@email.com", 5.00, "1", "fake street", "Wadebridge", "pl27 8DD");
//        this.registerCustomer((Customer) item);
//        item = new Customer("bob mann", "rich@email.com", 5.00, "1", "fake street", "Wadebridge", "pl27 8DD");
//        this.registerCustomer((Customer) item);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getCostPerKg() {
        return costPerKg;
    }

    public void setCostPerKg(double cost) {
        this.costPerKg = cost;
    }

    public int getID() {
        return ID;
    }

    public int generateID() {
        Random rand = new Random();

        int lowerBound = 0;
        int upperBound = 1000;

        int result = rand.nextInt(upperBound);

        return result;  
    }

     public ArrayList<Customer> getcustomers() {

         return arlCustomers;
    }

     public void setCustomers(ArrayList customers) 
     {
         arlCustomers = customers;
     }

    public void registerCustomer(Customer customer) {
        arlCustomers.add(customer);

    }

}

用您的arraylist和方法创建一个类以添加或删除等,并在arraylist和方法中添加static,并且您不需要该类的实例..并且您可以从任何类访问相同的列表。

static ArrayList<Customer> arlCustomers = new ArrayList<Customer>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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