0

我正在尝试序列化按钮矩阵(new JButton [6][6];),以便我可以将值保存到文件中,然后将它们重新加载到矩阵中。我在网上找到了成功保存数据的代码,但我无法加载数据并将其值返回到矩阵。

我尝试使用以下代码:

public class SaveListener implements ActionListener {
    public void actionPerformed(ActionEvent ab) {
        saveArray("customlevel", buttons);
    }

    public void saveArray(String filename, JButton[][] write) {
        try {
            FileOutputStream fos = new FileOutputStream(filename);
            GZIPOutputStream gzos = new GZIPOutputStream(fos);
            ObjectOutputStream out = new ObjectOutputStream(gzos);
            out.writeObject(write);
            out.flush();
            out.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

public class LoadListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        loadArray("customlevel", buttons);
    }
}

public JButton[][] loadArray(String filename, JButton[][] read) {
    try {
        FileInputStream fis = new FileInputStream(filename);
        GZIPInputStream gzis = new GZIPInputStream(fis);
        ObjectInputStream in = new ObjectInputStream(gzis);
        // in.readObject(read);
        JButton[][] load = (JButton[][]) in.readObject();
        in.close();
        return load;
    } catch (Exception e) {
        System.out.println(e);

    }
    return null;
}
4

2 回答 2

2

loadArray()你既传入一个数组又返回一个数组。传入的数组被忽略。您是否以某种方式期望传入的数组将被填充?

于 2013-02-21T15:35:07.553 回答
0

我认为混乱来自这样一个事实,即您从 loadArray() 方法返回加载的数组,但忽略了 ActionListener.performAction 函数中函数调用的结果。如果您希望按钮具有返回值,只需分配它,就这样做

buttons = loadArray(fileName)

于 2013-02-21T15:42:04.787 回答