Я создаю игру Судоку, и я пытаюсь предоставить варианты сохранения, сохранения и открытия игр. Я использую JFileChooser для этого. Я могу сохранить (или «сохранить как»), но когда я пытаюсь открыть сохраненный файл, я получаю сообщение об ошибке. Я новичок в программировании, и я надеюсь, что кто-то сможет определить проблему и рассказать мне о том, как читать содержимое доски Sudoku, когда я экономлю (а также как бороться с воссозданием судоку, когда я открываю файл). Я слышал, что есть более простой способ справиться с этим, используя InputStream/OutputStream вместо Reader/Writer ...Судоку игра, проблема сериализации
Вот мой код для внутреннего класса, который реализует это (я не знаю, есть ли способ опубликовать весь мой класс без превышения максимально допустимой для данного текстового поля):.
// this inner class provides a JMenuBar object at the top of
// the board
class MenuAtTop extends JMenuBar implements ActionListener{
// SudokuMain2 object we are dealing with
private SudokuMain2 main;
// the "File" menu
private JMenu fileMenu;
// the "New Game" option
private JMenuItem newGame;
// the "Open" option
private JMenuItem open;
// the "Save" option
private JMenuItem save;
// the "Save As" option
private JMenuItem saveAs;
// the "Reset" option
private JMenuItem reset;
// the "Quit" option
private JMenuItem quit;
// the ability to choose files
private JFileChooser choose;
// the saved file
// // compiler would not allow "static" keyword
private File fileSaved = null;
private Object opener;
// JDialog object to create a dialog box to prompt
// user for new game information
private JDialog createNewWin;
/**
* Constructs MenuAtTop object.
*
* @param m The SudokuMain2 object to be referred to.
*/
public MenuAtTop(final SudokuMain2 m) {
main = m;
opener = null;
choose = new JFileChooser();
// instantiate and bind to reference
fileMenu = new JMenu("File");
add(fileMenu);
// instantiate and bind to reference
newGame = new JMenuItem("New Game");
newGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.CTRL_MASK));
fileMenu.add(newGame);
newGame.addActionListener(this);
open = new JMenuItem("Open");
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
ActionEvent.CTRL_MASK));
fileMenu.add(open);
// add action listener to "Open" option
open.addActionListener(this);
save = new JMenuItem("Save");
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK));
fileMenu.add(save);
// //save.setEnabled(false);
// add action listener to "Save" option
save.addActionListener(this);
saveAs = new JMenuItem("Save As");
saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
ActionEvent.CTRL_MASK));
fileMenu.add(saveAs);
// add action listener to "Save As" option
saveAs.addActionListener(this);
reset = new JMenuItem("Reset");
reset.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
ActionEvent.CTRL_MASK));
fileMenu.add(reset);
// add action listener to "Reset" option
reset.addActionListener(this);
quit = new JMenuItem("Quit");
quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
ActionEvent.CTRL_MASK));
fileMenu.add(quit);
// add action listener to "Quit" option
quit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(quit)) {
closePrompt();
//main.win.dispose();
}
else if(e.getSource().equals(reset)) {
int n = JOptionPane.showConfirmDialog(main.win,
"Any player values will" +
" be lost. Proceed?",
"Warning!", 2);
if(n == JOptionPane.OK_OPTION) {
main.board.reset();
main.view.repaint();
}
}
else if(e.getSource().equals(saveAs)) {
saveAs();
}
else if(e.getSource().equals(save)) {
if(fileSaved == null) {
saveAs();
}
else {
try {
board.writeToStream(new FileOutputStream(fileSaved));
// main.board.setDirty(false);
} catch (Exception ex) {
JOptionPane.showMessageDialog(main.win, "Error saving file.");
}
}
}
else if(e.getSource().equals(open)) {
int returnVal = choose.showOpenDialog(main.win);
if(returnVal == JFileChooser.APPROVE_OPTION) {
boolean error = false;
File openFile = choose.getSelectedFile();
try {
FileInputStream fin = new FileInputStream(openFile);
ObjectInputStream ois = new ObjectInputStream(fin);
opener = ois.readObject();
} catch (Exception ex) {
JOptionPane.showMessageDialog(main.win, "Error opening file.");
error = true;
}
if(opener != null && opener instanceof SudokuBase){
main.west.remove(main.symbols);
main.east.remove(main.view);
//add in state information for new board
main.south.remove(main.rowColRegStates);
main.view = new SudokuView((SudokuBase) opener);
main.symbols = new SetSymbols(main.view);
//add in state information for new board
main.rowColRegStates = new ShowStates(main.view);
main.west.add(main.symbols);
main.east.add(main.view);
//add in state information for new board
main.south.add(main.rowColRegStates);
main.win.requestFocus();
fileSaved = openFile;
// main.board.setDirty(false);
} else {
if(error) {
JOptionPane.showMessageDialog(main.win, " Incorrect file type!");
}
}
}
// else: user cancelled
}
else if(e.getSource().equals(newGame)) {
setEnabled(false);
// create dialog box prompting for the new board information
createNewWin = new Dialog1(main, "Create New Board", true);
// make it visible
createNewWin.setVisible(true);
fileSaved = null;
}
}
// This method prompts the user to choose a file to save to,
// and then saves the file.
private int saveAs() {
boolean saveError;
int rtn = choose.showSaveDialog(main.win);
if(rtn == JFileChooser.APPROVE_OPTION) {
saveError = false;
File fileSaveAs = choose.getSelectedFile();
try {
board.writeToStream(new FileOutputStream(fileSaveAs));
} catch (Exception e) {
JOptionPane.showMessageDialog(main.win, "Error saving file.");
saveError = true;
}
if(!saveError) {
fileSaved = fileSaveAs;
// main.board.setDirty(false);
}
}
return rtn;
}
/**
* Asks the user if they want to save before closing if changes were made.
*/
private void closePrompt() {
if(true) { //board.isDirty()) {
int n = JOptionPane.showConfirmDialog(main.win, "Save game?");
if(n == JOptionPane.YES_OPTION) {
int saved = saveAs();
if(saved != JFileChooser.CANCEL_OPTION){
main.win.dispose();
}
}
else if(n == JOptionPane.NO_OPTION) {
main.win.dispose();
}
}
else
main.win.dispose();
}
}
Что ошибка вы получаете? – tbodt
* «Я получаю сообщение об ошибке». * Вы собираетесь поделиться с нами ошибкой или нам следует угадать? ОК .. для «TooManyKittensError», desex the tomcat из соседней двери. –
Объект, содержащий информацию для сохранения, является экземпляром класса 'SudokuMain2'? Покажите нам класс ... –