对于我的计算机科学课,我必须创建一个能够保存和加载的扫雷游戏。我尝试使用序列化但它没有结束工作(我没有得到任何错误,但是当我尝试保存或加载时没有任何反应,我无法找到任何保存的文件)。他没有说我们必须使用序列化,所以我很高兴听到其他方法来做到这一点!
谢谢!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class MineFrame extends JFrame implements java.io.Serializable
{
MinePanel myPanel;
JMenuBar menuBar;
public MineFrame()
{
setTitle("Minesweeper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
myPanel = new MinePanel();
getContentPane().add(myPanel);
menuBar = new JMenuBar();
getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu file = new JMenu("File");
menuBar.add(file);
JMenuItem save = new JMenuItem("Save");
save.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileOutputStream fileOut = new FileOutputStream("/Minesweeper/minesweeper.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(myPanel);
out.close();
fileOut.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
});
JMenu newGame = new JMenu("New Game");
file.add(newGame);
JMenu setDifficulty = new JMenu("Set Difficulty");
mnNewGame.add(setDifficulty);
//I left out the difficulty settings
file.add(save);
JMenuItem load = new JMenuItem("Load");
load.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileInputStream fileIn = new FileInputStream("/Minesweeper/minesweeper.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
myPanel = (MinePanel) in.readObject();
repaint();
in.close();
fileIn.close();
}
catch(IOException | ClassNotFoundException e1)
{
e1.printStackTrace();
}
}
});
file.add(load);
JMenuItem quit = new JMenuItem("Quit");
quit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
file.add(quit);
setVisible(true);
}
}
答案 0 :(得分:0)
我猜它正在运行它只是UI没有更新,试试这个(在你的加载尝试catch):
FileInputStream fileIn = new FileInputStream("/Minesweeper/minesweeper.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
//remove the old panel
getContentPane().remove(myPanel);
myPanel = (MinePanel) in.readObject();
//add the new panel
getContentPane().add(myPanel);
//revalidate
getContentPane().invalidate();
getContentPane().validate();
repaint();
in.close();
fileIn.close();