繁体   English   中英

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

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

好的,我是Java编程的新手,并且我不太了解文件读取/写入的概念。 我尝试查看有关Files的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();

    }

您必须使用定义的特定格式来写入文件:在志愿者类中添加序列化方法,然后可以遍历它们并序列化它们中的每一个。 字符串serialize()会将所有成员编码为字符串,然后可以在读取时(在Open上)进行重构。

一个示例可以是用逗号分隔的列表: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

这对您有意义吗? 通过简单的Google搜索,这些步骤都很简单

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

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

暂无
暂无

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

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