简体   繁体   中英

How I can share the same copy of ArrayList in 2 inner anonymous Classes?

Please, how I can share the same copy of ArrayList in 2 inner Classes?? picture of the GUI , I put two buttons : the first to"add patient" and I made it , but what the functionality I have to add to "retrieve" button with the same values registered in first button?

package my.firstProject;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;

public class PatientRecordUI extends javax.swing.JFrame {

    /**
     * Creates new form PatientRecordUI
     */
    public PatientRecordUI() {
        initComponents();
    }

    private void jButton1ActionPerformed(ActionEvent evt) {
        // TODO add your handling code here:
        String first, second, last;
        int bMonth, bDay, bYear, aMonth, aDay, aYear, fileNo;
        first = jTextField1.getText();
        second = jTextField2.getText();
        last = jTextField3.getText();

        bMonth = Integer.parseInt(jTextField4.getText());
        bDay = Integer.parseInt(jTextField5.getText());
        bYear = Integer.parseInt(jTextField6.getText());

        aMonth = Integer.parseInt(jTextField7.getText());
        aDay = Integer.parseInt(jTextField8.getText());
        aYear = Integer.parseInt(jTextField9.getText());
        fileNo = Integer.parseInt(jTextField10.getText());

        Date birth = new Date(bMonth, bDay, bYear);
        Date admissionDate = new Date(aMonth, aDay, aYear);
        Patient patient = new Patient(first, second, last, fileNo, birth, admissionDate);

        ArrayList<Patient> obj = new ArrayList<Patient>();
        obj.add(patient);
    }

    private void jButton2ActionPerformed(ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PatientRecordUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private JButton jButton1;
    private JButton jButton2;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JLabel jLabel3;
    private JLabel jLabel4;
    private JLabel jLabel5;
    private JLabel jLabel7;
    private JLabel jLabel8;
    private JPanel jPanel1;
    private JTextField jTextField1;
    private JTextField jTextField10;
    private JTextField jTextField11;
    private JTextField jTextField2;
    private JTextField jTextField3;
    private JTextField jTextField4;
    private JTextField jTextField5;
    private JTextField jTextField6;
    private JTextField jTextField7;
    private JTextField jTextField8;
    private JTextField jTextField9;
    // End of variables declaration
}

and here the Patient Class:

import java.util.Calendar;

public class Patient {
    private String firstName;
    private String secondName;
    private String lastName;
    private int fileNumber;
    private Date birthDate;
    private Date admissionDate;

    // constructor to initialize name, birth date and admission date

    public Patient(String first, String second, String last, int fileNo, Date dateOfBirth, Date dateOfAdmission) {
        firstName = first;
        secondName = second;
        lastName = last;
        fileNumber = fileNo;
        birthDate = dateOfBirth;
        admissionDate = dateOfAdmission;
    } // end Patient constructor

    public int getAage() {
        return Calendar.getInstance().get(Calendar.YEAR) - birthDate.getYear();

    }

    // convert Patient to String format
    public String toString() {
        return String.format("%s, %s %s   File No.:%d\n Admission: %s  age: %d\n\n", lastName, firstName, secondName,
                fileNumber, admissionDate, getAage());
    } // end method toString
} // end class Patient

and here the Date Class

    public class Date
    {
    private int month; // 1-12
    private int day;   // 1-31 based on month
    public  int year;  // any year

  // constructor: call checkMonth to confirm proper value for month; 
   // call checkDay to confirm proper value for day

   }
   public Date( int theMonth, int theDay, int theYear )
  {
  month = checkMonth( theMonth ); // validate month
  setYear(theYear); // could validate year
  day = checkDay( theDay ); // validate day

    } // end Date constructor

  // utility method to confirm proper month value
   private int checkMonth( int testMonth )
   {
     if ( testMonth > 0 && testMonth <= 12 ) // validate month
       return testMonth;
      else // month is invalid 
      { 
     System.out.printf( 
        "Invalid month (%d) set to 1.", testMonth );
     return 1; // maintain object in consistent state
      } // end else
    } // end method checkMonth

    // utility method to confirm proper day value based on month and year
     private int checkDay( int testDay )
    {
    int daysPerMonth[] = 
     { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    // check if day in range for month
    if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
     return testDay;

    // check for leap year
    if ( month == 2 && testDay == 29 && ( year % 400 == 0 || 
       ( year % 4 == 0 && year % 100 != 0 ) ) )
     return testDay;

    System.out.printf( "Invalid day (%d) set to 1.", testDay );
    return 1;  // maintain object in consistent state
   } // end method checkDay

 private void setYear(int testYear)
 {
 year = testYear < 0 ? 0 : testYear;
 }

 public int getYear()
 {
    return year;
 }
 // return a String of the form month/day/year
  public String toString()
  { 
  return String.format( "%d/%d/%d", month, day, year ); 
  } // end method toString

  } // end class Date

While you are declaring a variable inside a method it would be local to that method.

In this case whenever you will click Add Patient button it will create a new arraylist. So it will reset earlier values.

Instead of declaring the obj in method level , you should declare it in class level so that it will not be reset and all other method can access it (Which you want)

So, first of all, your jButton1ActionPerformed() method is creating a new array of patients and then adding a new patient to it every time it is called. That's not gonna be useful at all. You need to create one and only one array ever, and use it to store your patients.

Go to your PatientRecordUI class and add a new field like this:

public class PatientRecordUI extends javax.swing.JFrame {

    private ArrayList<Patient> patientsArray = new ArrayList<Patient>();

Now in your jButton1ActionPerformed() method, remove this part:

    ArrayList<Patient> obj = new ArrayList<Patient>();
    obj.add(patient);

And replace it with

    patientsArray.add(patient);

Now your program should be storing the patients correctly.

The next thing you want to do is create a method to retrieve patient data. I imagine this is what should be happening in your jButton2ActionPerformed() method.

To retrieve patient data, you first need a way to locate it based on the fileNumber property. My guess is that the user inputs the file number using the eleventh textfield, so the number would be

    int numberRequested = Integer.parseInt(jTextField11.getText());

Since you have the patients stored in an array, you should iterate each patient and look for one that has a file number equal to numberRequested . Once you find the patient, you simply get their info and show it in the interface.

One way to retrieve patient data is to put some getters in the Patient class. Otherwise, you could make the fields public. Up to you.

I won't detail how to do these latest steps - this should be enough to put you on track.

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