gpt4 book ai didi

java - 如何序列化 JButton [ ]

转载 作者:行者123 更新时间:2023-11-30 11:25:08 25 4
gpt4 key购买 nike

我目前正在用 Java 编写我的学校项目,你必须管理一个小村庄的经济。所以游戏看起来是这样的:有一个框架,其中有 49 个 SpecButtons(稍后解释)代表村庄的瓷砖。单击其中一个会打开一个构建菜单,您可以从中选择要在那里构建的建筑物类型等....

我创建了一个新类,它扩展了 JButton 类并实现了 Serializable,称为 SpacButtons。我在这个类中添加了两个整数、一个 Buildings 类类型的建筑变量(也是我创建的一个类)和一些方法。

SpecButtons buttons=new SpecButtons[49];

所以我必须使用序列化来保存游戏,这就是我尝试这样做的方式:

        private class SaveButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent button) {
try{
FileOutputStream fos = new FileOutputStream("saves.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);

for(int x = 0;x<49;x++){
oos.writeObject(buttons[x]);
}
oos.close();
fos.close();
}catch(IOException e){System.out.println("File Writing Error!");}

}
}

private class LoadButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent button) {

try{
FileInputStream fip = new FileInputStream("saves.ser");
ObjectInputStream oip = new ObjectInputStream(fip);
for(int x=0;x<49;x++){
buttons[x] = (SpecButtons) oip.readObject();
}
oip.close();
fip.close();
}catch(IOException e){System.out.println("File Reading Error!");}
catch(ClassNotFoundException ce){System.out.println("Class Not Found!");}
}
}

因此,它创建了 .ser 文件,但是当我尝试加载它时没有任何反应。如果你们知道如何让它发挥作用,我将不胜感激。

最佳答案

So, it creates the .ser file, but when I try to load it nothing happens.

假设您的按钮已正确反序列化,您应该在从 .ser 文件加载后将它们添加到您的主框架。

for(int x=0;x<49;x++){
buttons[x] = (SpecButtons) oip.readObject();
}
// Add the buttons to the main frame where you would like them to appear...

关于java - 如何序列化 JButton [ ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com