简体   繁体   中英

How to Save/Open an ArrayList of objects using JFileChooser?

Okay so I'm kind of new to Java programming, and I don't quite understand the concepts of file reading/writing. I've tried looking at the docs.oracle webpages about Files, but I found they aren't really helpful considering what I'm trying to do is kind of different.

I have these 3 files: CVolunteer, CDialog, and TestDialog. CVolunteer creates and object of a person who can volunteer to tutor students. CDialog manages the adding/editing of the volunteer. TestDialog displays a JList of volunteers and allows the user to edit, add, remove, or clear the list. I have those 3 classes working perfectly and will display them below (sorry they're long!).

Here's what I need help with... I added two buttons to the main window, "Save" and "Open". At any time, the user should be able to save the current JList of volunteers. When "Save" is clicked, a JFileChooser window should pop up and ask the user for a filename where all the volunteer objects will be saved. When the user clicks "Open", another JFileChooser window should pop up and ask the user what file they want to open. The volunteers currently in the main window will be erased and the volunteers from the selected file will take their place. I'm not sure if I need to use Serialization or not....

If anyone could help explain how to accomplish this or help me write the code to handle the "Save"/"Open" events, I would really appreciate it! Thanks in advance:)

I believe the only file that needs changing is TestDialog, I included the others in case someone wants to try to run it

***Sorry if there are any indentation errors, I had to do it all by hand in this dialog box CVolunteer.java

public class CVolunteer {
    int volNum;
    String name;
    int sub, volDays, trans;

    public CVolunteer(int vNum, String vName, int subj, int days, int needTrans){
        volNum = vNum;
        name = vName;
        sub = subj;
        volDays = days;
        trans = needTrans;
    }

    private String subjectToString()
    {
        switch (sub){
        case 0: 
            return "Math";
        case 1:
            return "Science";
        case 2:
            return "English";
        case 3:
            return "History";
        }

        return " ";
    }

    private String volDaysToString()
    {
        String str = "";
        str +=((volDays&1)!=0)?"M":"-";
        str +=((volDays&2)!=0)?"T":"-";
        str +=((volDays&4)!=0)?"W":"-";
        str +=((volDays&8)!=0)?"R":"-";

        return str;
    }

    private String transToString()
    {
        switch(trans)
        {
        case 0:
            return "Yes";
        case 1:
            return "No";
        }

        return " ";
    }

    public String getVolunteerLine()
    {
        return String.format("%05d                      %-30s%-30s%-30s%s", 
                volNum, name, subjectToString(), volDaysToString(), transToString());
    }

}

CDialog.java

import java.awt.Container;
import java.awt.event.*;
import javax.swing.*; 


public class CDialog extends JDialog implements ActionListener
{
    private JLabel label1;
    private JLabel lNum;
    private JLabel label2;
    private JTextField tfName;

    private JLabel label3;
    private ButtonGroup  subGroup;
    private JRadioButton rbMath;
    private JRadioButton rbScience;
    private JRadioButton rbEnglish;
    private JRadioButton rbHistory;

    private JLabel label4;
    private JCheckBox cbMonday;
    private JCheckBox cbTuesday;
    private JCheckBox cbWednesday;
    private JCheckBox cbThursday;

    private JLabel label5;
    private ButtonGroup transGroup;
    private JRadioButton rbYes;
    private JRadioButton rbNo;

    private JButton okButton = null;
    private JButton cancelButton = null;

    private boolean cancelled = true;
    public boolean isCancelled() {return cancelled;}

    private CVolunteer answer;
    public CVolunteer getAnswer() {return answer;}

    public CDialog(JFrame owner, String title, CVolunteer vol)
    {
        super(owner, title, true);

        Container c = getContentPane();
        c.setLayout(null);

        label1 = new JLabel ("Volunteer Number:");
        label1.setSize(140,20);
        label1.setLocation(40,40);
        c.add(label1);

        lNum = new JLabel(String.format("%05d", vol.volNum));
        lNum.setSize(40,20);
        lNum.setLocation(150,40);
        c.add(lNum);

        label2 = new JLabel ("Volunteer Name: ");
        label2.setSize(100,20);
        label2.setLocation(40,90);
        c.add(label2);

        tfName = new JTextField(vol.name);
        tfName.setSize(120,20);
        tfName.setLocation(140,90);
        c.add(tfName);

        int x,y;
        int w,h;
        x=4;
        y=150;
        w=180;
        h=20;

        label3 = new JLabel("Subject: ");
        label3.setSize(85,13);
        label3.setLocation(x,y);
        c.add(label3);

        rbMath = new JRadioButton("Math", vol.sub==0);
        rbMath.setSize(w,h);
        rbMath.setLocation(x+16,y+30);
        c.add(rbMath);

        rbScience = new JRadioButton("Science", vol.sub==1);
        rbScience.setSize(w,h);
        rbScience.setLocation(x+16,y+66);
        c.add(rbScience);

        rbEnglish = new JRadioButton("English", vol.sub==2);
        rbEnglish.setSize(w,h);
        rbEnglish.setLocation(x+16,y+102);
        c.add(rbEnglish);

        rbHistory = new JRadioButton("History", vol.sub==3);
        rbHistory.setSize(w,h);
        rbHistory.setLocation(x+16,y+138);
        c.add(rbHistory);

        subGroup = new ButtonGroup();
        subGroup.add(rbMath);
        subGroup.add(rbScience);
        subGroup.add(rbEnglish);
        subGroup.add(rbHistory);

        x=220;
        y=150;
        w=120;
        h=20;
        label4 = new JLabel("Days Available: ");
        label4.setSize(w,h);
        label4.setLocation(x,y);
        c.add(label4);

        cbMonday = new JCheckBox("Monday (M)", (vol.volDays&1)!=0);
        cbMonday.setSize(w,h);
        cbMonday.setLocation(x+6,y+30);
        c.add(cbMonday);

        cbTuesday = new JCheckBox("Tuesday (T)", (vol.volDays&2)!=0);
        cbTuesday.setSize(w,h);
        cbTuesday.setLocation(x+6,y+66);
        c.add(cbTuesday);

        cbWednesday = new JCheckBox("Wednesday (W)", (vol.volDays&4)!=0);
        cbWednesday.setSize(w,h);
        cbWednesday.setLocation(x+6,y+102);
        c.add(cbWednesday);

        cbThursday = new JCheckBox("Thursday (R)", (vol.volDays&8)!=0);
        cbThursday.setSize(w,h);
        cbThursday.setLocation(x+6,y+138);
        c.add(cbThursday);

        x=480;
        y=150;
        w=180;
        h=20;
        label5 = new JLabel("Need Transport? :");
        label5.setSize(150,13);
        label5.setLocation(x,y);
        c.add(label5);

        rbYes = new JRadioButton("Yes", vol.trans==0);
        rbYes.setSize(w,h);
        rbYes.setLocation(x+12,y+30);
        c.add(rbYes);

        rbNo = new JRadioButton("No", vol.trans==1);
        rbNo.setSize(w,h);
        rbNo.setLocation(x+12,y+66);
        c.add(rbNo);

        transGroup = new ButtonGroup(); 
        transGroup.add(rbYes);
        transGroup.add(rbNo);

        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(this);
        cancelButton.setSize(100,50);
        cancelButton.setLocation(116,380);
        c.add(cancelButton);

        okButton = new JButton("OK");
        okButton.addActionListener(this);
        okButton.setSize(100,50);
        okButton.setLocation(400,380);
        c.add(okButton);

        setSize(700,480);
        setLocationRelativeTo(owner);
        setVisible(true);







    }


    public void actionPerformed(ActionEvent e) 
    {
        if (e.getSource()==okButton) {
            int num=Integer.parseInt(lNum.getText());

            String name=tfName.getText();

            int subj=-1;
            if (rbMath.isSelected()) subj = 0;
            if (rbScience.isSelected()) subj = 1;
            if (rbEnglish.isSelected()) subj = 2;
            if (rbHistory.isSelected()) subj = 3;

            int days=0;
            if (cbMonday.isSelected()) days |= 1;
            if (cbTuesday.isSelected()) days |= 2;
            if (cbWednesday.isSelected()) days |= 4;
            if (cbThursday.isSelected()) days |= 8;

            int tran=0;
            if (rbYes.isSelected()) tran = 0;
            if (rbNo.isSelected()) tran = 1;

            answer=new CVolunteer(num, name, subj, days, tran);

            cancelled = false;
            setVisible(false);
        }
        else if(e.getSource()==cancelButton) {
            cancelled = true;
            setVisible(false);
        }

    }


}

TestDialog.java

import java.awt.event.*;

import javax.swing.*;

import java.awt.*;
import java.io.*;
import java.util.ArrayList;


public class TestDialog extends JFrame implements ActionListener
{
    JLabel  myLabel1  = null;
    JLabel  myLabel2  = null;
    JLabel  myLabel3  = null;
    JLabel  myLabel4  = null;
    JLabel  myLabel5  = null;
    JLabel  myLabel6  = null;

    File fileName = new File("Volunteers.txt");

    ArrayList<CVolunteer> volArray;
    private DefaultListModel volunteers;
    JList volList;
    JScrollPane scrollPane = null;

    JButton bAdd = null;
    JButton bEdit = null;
    JButton bRemove = null;
    JButton bClear = null;
    JButton bSave = null;
    JButton bOpen = null;

    int volNumb;

    public TestDialog()
    {
        super("Volunteer Info");

        Container c = getContentPane();
        c.setLayout(null);

        myLabel1 = new JLabel("Vol Number");
        myLabel1.setSize(200,50);
        myLabel1.setLocation(100,10);
        c.add(myLabel1);

        myLabel2 = new JLabel("Vol Name");
        myLabel2.setSize( 200, 50 );
        myLabel2.setLocation( 200, 10 );
        c.add(myLabel2);

        myLabel3 = new JLabel("Subject");
        myLabel3.setSize( 200, 50 );
        myLabel3.setLocation( 310, 10);
        c.add(myLabel3);

        myLabel4 = new JLabel("Vol Days");
        myLabel4.setSize( 200, 50 );
        myLabel4.setLocation( 400, 10 );
        c.add(myLabel4);

        myLabel5 = new JLabel("Transport");
        myLabel5.setSize( 200, 50 );
        myLabel5.setLocation( 500, 10 );
        c.add(myLabel5);

        volArray = new ArrayList<CVolunteer>();
        volunteers = new DefaultListModel();
        volList = new JList(volunteers);
        volList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        scrollPane = new JScrollPane(volList);
        scrollPane.setSize(500,300);
        scrollPane.setLocation(100,50);
        c.add(scrollPane);

        bAdd = new JButton("Add");
        bAdd.setSize( 100, 50 );
        bAdd.setLocation( 20, 400 );
        bAdd.addActionListener(this);
        c.add(bAdd);

        bEdit = new JButton("Edit");
        bEdit.setSize( 100, 50 );
        bEdit.setLocation( 150, 400 );
        bEdit.addActionListener(this);
        c.add(bEdit);

        bRemove = new JButton("Remove");
        bRemove.setSize( 100, 50 );
        bRemove.setLocation( 280, 400 );
        bRemove.addActionListener(this);
        c.add(bRemove);

        bClear = new JButton("Clear");
        bClear.setSize( 100, 50 );
        bClear.setLocation( 410, 400 );
        bClear.addActionListener(this);
        c.add(bClear);

        bSave = new JButton("Save");
        bSave.setSize( 100, 50 );
        bSave.setLocation( 540, 400 );
        bSave.addActionListener(this);
        c.add(bSave);

        bOpen = new JButton("Open");
        bOpen.setSize( 100, 50 );
        bOpen.setLocation( 670, 400 );
        bOpen.addActionListener(this);
        c.add(bOpen);

        setSize( 800, 600 );
        setLocation( 100, 100 );
        setVisible(true);

        volNumb = 0;

    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==bAdd) {
            volNumb++;
            CVolunteer defaultVol = new CVolunteer(volNumb, "", 1, 0, 0); 
            CDialog dialogWnd = new CDialog(this, "Add a Volunteer", defaultVol);
            if (!dialogWnd.isCancelled()) {
                volArray.add(dialogWnd.getAnswer());
                volunteers.addElement(dialogWnd.getAnswer().getVolunteerLine());
                volList.setSelectedIndex(volunteers.size()-1);
                volList.ensureIndexIsVisible(volunteers.size()-1);
            }
        }
        else if(e.getSource()==bEdit) {
            int index=volList.getSelectedIndex();
            if (index>=0) {
                CDialog dialogWnd = new CDialog (this, "Edit a Volunteer", volArray.get(index));
                if (!dialogWnd.isCancelled()) {
                    volArray.set(index, dialogWnd.getAnswer());
                    volunteers.set(index, dialogWnd.getAnswer().getVolunteerLine());
                }
            }
        }
        else if(e.getSource()==bRemove) {
            int index=volList.getSelectedIndex();
            if (index>=0) {
                volArray.remove(index);
                volunteers.remove(index);
                if (volunteers.size()>0) {
                    if (index==volunteers.size()) {
                        index--;
                        }
                    volList.setSelectedIndex(index);
                    volList.ensureIndexIsVisible(index);
                }
            }
        }
        else if(e.getSource()==bClear) {
            volArray.clear();
            volunteers.clear();
        }

        else if (e.getSource()==bSave)
        {

            //my sorry attempt at writing a file.. ignore this!
            try {
                FileWriter fw = new FileWriter(fileName);
                Writer output = new BufferedWriter(fw);
                int size = volArray.size();
                for (int i = 0; i<size; i++)
                {
                    output.write(volArray.get(i).getVolunteerLine() + "\n");
                }
                output.close();
            } 
            catch (Exception e1) {
                // TODO Auto-generated catch block

            }
            final JFileChooser fc = new JFileChooser();

        }

        else if (e.getSource()==bOpen)
        {

        }
    }

    public static void main(String[] args) {
        TestDialog mainWnd = new TestDialog();
    }


}

EDIT:

Here is some attempted code for my "Save" Button.... I still don't know if this is on the right track or not! It doesn't seem to be doing anything

else if (e.getSource()==bSave)
    {

        try 
        {
            FileOutputStream fileOut = new FileOutputStream("???");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            for(int i=0; i<volArray.size(); i++)
            {
                out.writeObject(volArray.get(i).getVolunteerLine());

            }
            out.close();
            fileOut.close();

        } catch (Exception e1) {
            // TODO Auto-generated catch block

        }
        final JFileChooser fc = new JFileChooser();

    }

You have to use a specific format that you define to write in your file : Add a serialize method in you volunteer class then you can iterate over them and serialize each of them. String serialize() will encode all the members as a string then you can reconstruct at reading (on Open).

An example could be a coma separated list : member1=xxx, member2=xxx, ... Or xml or json for more ease :)

At reading, it's the opposite, parse the content of the file and build your volunteers back !

Edit:

Saving:
Open a file in write mode
write all your n volunteers
at this point you should have n lines in your file
close the file

Reading:
Open your file in reading mode
Read it line by line
For each line
 split over ','
 build your volunteer
 add it to volArray
close your file

Does it make sense for you ? Each of these steps are trivial with a simple google search

Edit : Final JFileChooser fc = new JFileChooser();

if (returnVal == JFileChooser.APPROVE_OPTION) {
  File file = fc.getSelectedFile();
  //This is where a real application would open the file.
  log.append("Opening: " + file.getName() + "." + newline);
  // Here you can open the file and write to it

  //



} else {
  log.append("Open command cancelled by user." + newline);
}

You can do the same when on open, select the file then read from it

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