我创建了这两个函数,并将它们添加到按钮内的动作侦听器中。目的是创建一个序列化文件,并将Jlist中的内容写入该文件。程序关闭时,应使用序列化文件中的内容填充jlist。由于某种原因,它无法正常工作。任何人都可以看到有什么问题吗?
以下是代码:
JButton btnAdd = new JButton("Add"); // Setting what is written on the button
btnAdd.addActionListener(new ActionListener() { // implementing an action listener
public void actionPerformed(ActionEvent arg0) {
patientname = textField.getText(); // Getting the patient name from the textfield
patientaddress = textField_1.getText();
patientphone = textField_2.getText();
textField.setText(""); // Setting the textfield to be blank so that the user can input there name address etc..
textField_1.setText("");
textField_2.setText("");
patientid = patientid + 1;//Implementing the id to add 1 every time another id is added
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid); // Populating the array list patientlist with the users input
patientList.add(patient); // Adding the patient's details to the patientlist
patientListModel.addElement(patient); // adds the patient's details to the list model
}
public void onSave(List<Patient> PatientList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("PatientList.ser")));
out.writeObject(PatientList);
out.flush();
}
catch (IOException e) {
// handle exception
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// handle exception
}
}
}
}
public List<Patient> onLoad() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("PatientList.ser")));
return (List<Patient>) in.readObject();
}
catch (IOException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// handle exception
}
}
}
return null;
}
});
btnAdd.setBounds(0, 86, 65, 23);
contentPane.add(btnAdd);
/////////////////
这是我的耐心课:
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}