java - Java GUI 中的数组反序列化问题

标签 java user-interface serialization arraylist deserialization

现在我需要一些帮助来序列化我的数组列表。现在我已经设法使序列化方面正常工作(至少我认为),现在我的问题在于反序列化对象。我正在制作一个小型地址簿程序。我有一个组合框,用于存储地址,上面有三个文本框,用户在其中输入:姓名、地址和电话号码。出于测试目的,我有一个保存和加载按钮。保存按钮保存联系人,加载按钮加载以前的 session 联系人。现在除了反序列化之外的所有内容都可以工作,我想知道如何继续进行。

我的代码如下:

import java.awt.EventQueue;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;


public class Address_Book {

    private JFrame frame;
    private JTextField newName;
    private JTextField newAddress;
    private JTextField newPhoneAddress;
    ArrayList<Book> test = new ArrayList<Book>();
    ArrayList<Book> array = new ArrayList<Book>();

    File addBook = new File("addBook.txt");

    final JComboBox<String> comboBox = new JComboBox<String>();
    final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Address_Book window = new Address_Book();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Address_Book() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {         
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        newName = new JTextField();
        newName.setBounds(10, 29, 107, 20);
        frame.getContentPane().add(newName);
        newName.setColumns(10);

        JLabel lbl1 = new JLabel("Enter New Name:");
        lbl1.setBounds(10, 11, 107, 14);
        frame.getContentPane().add(lbl1);

        JLabel lbl2 = new JLabel("Enter New Address:");
        lbl2.setBounds(136, 11, 130, 14);
        frame.getContentPane().add(lbl2);

        newAddress = new JTextField();
        newAddress.setColumns(10);
        newAddress.setBounds(136, 29, 107, 20);
        frame.getContentPane().add(newAddress);

        newPhoneAddress = new JTextField();
        newPhoneAddress.setColumns(10);
        newPhoneAddress.setBounds(262, 29, 162, 20);
        frame.getContentPane().add(newPhoneAddress);

        JLabel lbl3 = new JLabel("Enter New Phone number:");
        lbl3.setBounds(262, 11, 162, 14);
        frame.getContentPane().add(lbl3);

        JButton btnAddNewContact = new JButton("Add new contact");
        btnAddNewContact.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent arg0) {
                test.add((new Book(newName.getText(), newAddress.getText(), newPhoneAddress.getText())));

                //mergesort.mergesort(test, 0, test.size() - 1);

                model.removeAllElements();
                for(int i=0; i < test.size();i++){
                    model.addElement(test.get(i).getContact()); 
                }
                comboBox.setModel(model);

                newName.setText(""); 
                newAddress.setText("");
                newPhoneAddress.setText("");
            }
        });
        btnAddNewContact.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
            }
        });
        btnAddNewContact.setBounds(10, 53, 414, 23);
        frame.getContentPane().add(btnAddNewContact);

        JLabel lbl4 = new JLabel("Current Contacts:");
        lbl4.setBounds(10, 87, 107, 14);
        frame.getContentPane().add(lbl4);

        frame.getContentPane().add(comboBox);


            comboBox.setModel(model);
            comboBox.setBounds(10, 101, 414, 20);
            comboBox.setSelectedIndex(test.size()-1);

            JButton btnLoad = new JButton("Load");
            btnLoad.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {

                    try {
                        /* Read objects */

                        FileInputStream in = new FileInputStream(addBook);
                        ObjectInputStream readIn = new ObjectInputStream(in);

                        array = (ArrayList<Book>) readIn.readObject();
                        readIn.close(); 

                        for(int i=0; i < array.size();i++){
                            model.addElement(array.get(i).getContact());    
                        }
                        comboBox.setModel(model);
                    }catch(Exception e1){
                        e1.printStackTrace();
                    }

                }
            });
            btnLoad.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                }
            });
            btnLoad.setBounds(10, 132, 89, 23);
            frame.getContentPane().add(btnLoad);

            JButton btnSave = new JButton("Save");
            btnSave.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent arg0) {
                    /* write objects */
                    try{

                        FileOutputStream out = new FileOutputStream(addBook);
                        ObjectOutputStream writeAdd = new ObjectOutputStream(out);
                        writeAdd.writeObject(test);
                        writeAdd.close();

                    }catch(Exception e){

                    }
                }
            });
            btnSave.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                }
            });
            btnSave.setBounds(109, 132, 89, 23);
            frame.getContentPane().add(btnSave);
    }
}

这是我的对象:

public class Book implements Comparable {
     private String flName, Address, pNumber;

    public Book(String Name, String address, String phoneNumber ){
        setFlName(Name);
        setAddress(address);
        setpNumber(phoneNumber);
    }

    public String getpNumber() {
        return pNumber;
    }

    public void setpNumber(String pNumber) {
        this.pNumber = pNumber;
    }

    public String getAddress() {
        return Address;
    }

    public void setAddress(String address) {
        Address = address;
    }

    public String getFlName() {
        return flName;
    }

    public void setFlName(String flName) {
        this.flName = flName;
    }  

    public String getContact() {
        return flName + ", " + Address + ", " + pNumber;
    }

    public int compareTo(Object c) {
        Book testBook = (Book)c;

        if (testBook.getFlName().compareTo(this.getFlName()) < 0){
            return(-1);
        }else if(testBook.getFlName().compareTo(this.getFlName()) == 0){
            return(0);
        }else{
            return(1);
        }
    }

}

下一个代码片段位于我的 Address_Book 类中,这是我给您的第一个代码,这只是为了更容易找到我从哪里加载它。

JButton btnLoad = new JButton("Load");
            btnLoad.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {

                    try {
                        /* Read objects */

                        FileInputStream in = new FileInputStream(addBook);
                        ObjectInputStream readIn = new ObjectInputStream(in);

                        array = (ArrayList<Book>) readIn.readObject();
                        readIn.close(); 

                        for(int i=0; i < array.size();i++){
                            model.addElement(array.get(i).getContact());    
                        }
                        comboBox.setModel(model);
                    }catch(Exception e1){
                        e1.printStackTrace();
                    }

                }
            });
            btnLoad.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                }
            });
            btnLoad.setBounds(10, 132, 89, 23);
            frame.getContentPane().add(btnLoad);

感谢您抽出宝贵的时间,如果您有任何疑问,请随时询问。 :)

最佳答案

  • 您的 Book 类未实现可序列化。修复此问题,因为这是导致异常的原因,也是您当前尝试序列化 ArrayList<Book> 的主要原因。失败了。
  • Google 搜索并阅读序列化教程。
  • 再次强调,当您应该使用 ActionListener 时,不要在 JButton 上使用 MouseListener。这不会导致您的问题,但如果不解决,将会导致 future 的问题。请阅读有关如何使用 JButtons 的 Java 教程,因为那里有非常详细的解释。
  • 再次强调,当您尝试向已经很复杂的程序实现新的复杂功能时,请首先隔离该复杂程序,以便在将其添加到更大的程序之前隔离并修复任何问题。如果您的新代码导致错误,则更是如此。

关于java - Java GUI 中的数组反序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11041453/

相关文章:

multithreading - Javafx 几个 GUI 线程 - 进度指示器

user-interface - 我在哪里可以找到这个 unicode 字符?

c++ - 使用私有(private)成员 boost 派生类的序列化

.net - 对于 .NET 中的序列化,我应该使用 JavaScriptSerializer 和 XmlSerializer 还是它们对应的 DataContract?

php - 在 PHP/MySQL 中存储大量表单数据的最佳方式?

java - 使用 Java 正则表达式自定义 HTML img 标签

调用函数时发生 Java 空指针异常

c++ - Qt QAbstractButton setDown 干扰 grabMouse

java - 无需任何 Google 服务即可在 Android 上进行语音识别和语音转文本

java - 当字段名称与局部变量相同时如何访问字段?