如何使用JFileChooser保存/打开对象的ArrayList?

时间:2014-04-02 22:05:42

标签: java file-io arraylist jfilechooser

好的,所以我对Java编程很陌生,而且我不太了解文件读/写的概念。我已经尝试查看关于文件的docs.oracle网页,但我发现它们并不是真的有用,考虑到我想做的事情有点不同。

我有这3个文件:CVolunteer,CDialog和TestDialog。 CVolunteer创建和反对可以自愿辅导学生的人。 CDialog管理志愿者的添加/编辑。 TestDialog显示志愿者的JList,并允许用户编辑,添加,删除或清除列表。我有3个班级完美地工作,并将在下面显示(对不起,他们很长!)。

这是我需要帮助的......我在主窗口添加了两个按钮,“保存”和“打开”。在任何时候,用户都应该能够保存当前的志愿者JList。单击“保存”时,将弹出一个JFileChooser窗口并询问用户是否存储了所有志愿者对象的文件名。当用户单击“打开”时,将弹出另一个JFileChooser窗口并询问用户他们要打开哪个文件。目前在主窗口中的志愿者将被删除,所选文件中的志愿者将取代他们的位置。我不确定是否需要使用序列化......

如果有人可以帮助解释如何完成此操作或帮助我编写代码来处理“保存”/“打开”事件,我将非常感激!在此先感谢:)

我相信唯一需要更改的文件是TestDialog,我包含了其他文件以防有人想要尝试运行它

***对不起,如果有任何缩进错误,我必须在此对话框中手动完成 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();
    }


}

编辑:

这是我的“保存”按钮的一些尝试代码....我仍然不知道这是否在正确的轨道上!它似乎没有做任何事情

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

    }

1 个答案:

答案 0 :(得分:0)

您必须使用您定义的特定格式在文件中写入: 在志愿者课程中添加序列化方法,然后您可以迭代它们并序列化它们。 String serialize()会将所有成员编码为字符串,然后您可以在读取时重新构建(在打开时)。

示例可以是逗号分隔列表:member1 = xxx,member2 = xxx,... 或者xml或json更容易:)

在阅读时,相反,解析文件的内容并建立志愿者!

编辑:

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

对你有意义吗?通过简单的谷歌搜索

,每个步骤都是微不足道的

编辑:     最终的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);
}

您可以在打开时执行相同操作,选择文件然后从中读取