如何将整个类存储在 HashMap 中及其所有变量保存到文件中?

问题描述

我有一个这样的 HashMap:HashMap<String,JPanel>

我有 6 种类型的页面。它们都扩展了 JPanel。

我使用以下代码将此充满 JPanel 的 HashMap 保存到文本文件 (.txt):

public static void writeJTreetoFile(final File f) {
  //serialization
    final FileOutputStream file;
    try {
        // write HashMap to file
        File hashF = new File(f.toString().replace(".txt","HashMap.txt"));
        final FileOutputStream hashFile = new FileOutputStream(hashF);
        ObjectOutputStream hashOut = new ObjectOutputStream(hashFile);
        hashOut.writeObject(implMainPage.getHashMap());
        hashOut.close();

        }catch (FileNotFoundException e) {
        e.printstacktrace();

        }catch (IOException e) {
        e.printstacktrace();
    }
    
}

我使用以下代码从保存的文件中读取 HashMap:

public static void readJTreeFromFile(File f) {
    //deserialization
    final FileInputStream file;
    try {
        
        // read HashMap from file
        File hashF = new File(f.toString().replace(".txt","HashMap.txt"));
        final FileInputStream hashFile = new FileInputStream(hashF);
        ObjectInputStream hashIn = new ObjectInputStream(hashFile);
        HashMap<String,JPanel> hashMap = (HashMap<String,JPanel>)hashIn.readobject();
        implMainPage.setHashMap(hashMap);
        hashIn.close();
        
        } catch (FileNotFoundException e) {
        e.printstacktrace();

        }catch (IOException e) {
        e.printstacktrace();

        }catch (ClassNotFoundException e) {
        e.printstacktrace();
        } 
}

可以显示面板,但按下时不会执行 JButton 的 actionListeners 中的函数

我相信当 JPanel 被保存时,它只是保存了它们的外观,而不是整个类。

如何将整个类及其所有变量保存到文件中?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)