Load方法返回一个空白的java窗口

时间:2014-12-19 16:22:16

标签: java serialization

我一直致力于保存和加载方法。它的目的是保存游戏类状态,然后在调用loadBoard时返回保存的游戏。当我加载游戏时,它返回一个空白的Java窗口。没有错误抛出。

Here is what it returns.

保存方法:

  public void saveGame(){

    GameBoard b = new GameBoard();
    try {
        System.out.println("Creating File/Object output stream...");
        FileOutputStream fileOut = new FileOutputStream("mstate.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);

        System.out.println("Writing GameBoard Object...");
        out.writeObject(b);

        System.out.println("Save Successful...\n");
        out.close();
        fileOut.close();

    } catch(FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IO Exception!");
        e.printStackTrace();
    } 
}

加载方法:

public void loadBoard()throws IOException, ClassNotFoundException {
    GameBoard b = new GameBoard();
     try {
    System.out.println("Creating File/Object input stream...");

    FileInputStream fileIn = new FileInputStream("mstate.ser");
    ObjectInputStream in = new ObjectInputStream(fileIn);

    System.out.println("Loading GameBoard Object...");
    GameBoard obj = (GameBoard)in.readObject();


    System.out.println("Load Successful...\n");
    in.close();
    fileIn.close();
    b.setVisible(true);



     } catch(FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IO Exception!");
        e.printStackTrace();
    }
}

GameBoard Class:

public class GameBoard extends JFrame implements Serializable
{
//MENU ITEMS
private JFrame frame;
private JMenuBar menubar = new JMenuBar();
private JTable table;

//FIELDS USED FOR GAMEPLAY
private int x;
private int y;
private boolean mineTrue;
private boolean triedTrue;
private static int boardsize = 8; 
private  int numberOfMines = 10;
public static final int Empty = 0;
public static final int Mine = -1;
public static final int Flag = -2;
public static final int FMine = -3;
public static final int RevealedMine = -4;
public static final int RevealedEmpty = -5;
// SIZE OF BUTTONS
private int gridsize = 45;
// ARRAY FOR THE BUTTONS
private JButton[][] buttons;
private int[][] board;
//VARIABLE USED FOR LABELS
private static int noGamesPlayed = 0;
private static int noGamesWon = 0;
private int mine = 10;
private static int minesLeft = 10;
private static int score = 1;
private static String playername;
// GAME STATUS
private boolean gamegoing = true;
// GAME LABELS

private JLabel space = new JLabel("");
private JTextField nameEnter = new JTextField("Enter name here: ");
private JButton saveName = new JButton("Play");
private JLabel namelabel = new JLabel("Player 1: ");
private JLabel scorelabel = new JLabel("0 points ");
private JLabel status = new JLabel("Game in Progress: ");
private JLabel gamesPlayed = new JLabel("Games Played: " + noGamesPlayed);
private JLabel gamesWon = new JLabel("Games Won : " + noGamesWon);
private JLabel noMines = new JLabel("Number of Mines: " + minesLeft);

/**
 * Constructor 
 */
public GameBoard()
{
    makeFrame();

}


private void makeFrame()
{
    frame = new JFrame("MineSweeper");

    //SETTING LAYOUT MANAGER
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(menubar, BorderLayout.NORTH);
    frame.getContentPane().setBackground(Color.BLACK);

    // SET UP OF THE GAME PANEL TO LEFT WITH GRIDLAYOUT
    JPanel gamePanel1 = new JPanel(new GridLayout(boardsize, boardsize));
    // CREATES BUTTONS, CREATES ACTIONLISTENER FOR EACH X,Y GRID POSITION
    buttons = new JButton[gridsize][gridsize];
    board = new int[9][9];
    for (int a = 0; a < boardsize; a++) 
        for (int b = 0; b < boardsize; b++) {
            buttons[a][b] = new JButton("");
            buttons[a][b].setPreferredSize(new Dimension(47, 47));
            gamePanel1.add(buttons[a][b]);
            Color brown = new Color(99,66,33    );
            buttons[a][b].setBackground(brown);
            buttons[a][b].addMouseListener(new MouseListener(a,b));
            setx(a);
            sety(b);
            settried(false);
            setmine(false);

    }

    contentPane.add(gamePanel1, BorderLayout.CENTER);

    // ASSIGNS THE MINES TO THE GRID
    assignmines();

    //UPDATES THE LABELS
    updateGamesPlayed() ;
    UpdateName();

    // SET UP OF THE GAME PANEL TO THE RIGHT. ADDING THE LABELS
    Box gamePanel = Box.createVerticalBox();
    add(gamePanel);
    ImageIcon imgThisImg = new ImageIcon("images/logo.jpg");

    space.setIcon(imgThisImg);;
    gamePanel.add(space);
    gamePanel.add(nameEnter);
    nameEnter.setMaximumSize(new Dimension(Integer.MAX_VALUE, nameEnter.getMinimumSize().height));
    gamePanel.add(saveName);
    saveName.setBackground(Color.GRAY);
    saveName.setForeground(Color.YELLOW);
    gamePanel.add(namelabel);
    namelabel.setForeground(Color.WHITE);
    gamePanel.add(scorelabel);
    scorelabel.setForeground(Color.WHITE);
    gamePanel.add(gamesPlayed);
    gamesPlayed.setForeground(Color.WHITE);
    gamePanel.add(gamesWon);
    gamesWon.setForeground(Color.WHITE);
    gamePanel.add(status);
    status.setForeground(Color.YELLOW);
    gamePanel.add(noMines);
    noMines.setForeground(Color.WHITE);
    contentPane.add(gamePanel, BorderLayout.EAST);

    contentPane.add(status, BorderLayout.SOUTH);
    // DISPLAYS THE FRAME AND ALLOWS FOR RESIZING
    frame.pack();
    frame.setVisible(true);

    makeMenuBar();
}

// MAKING THE GAME MENU BAR
public void makeMenuBar(){

    JMenu menu; 
    JMenuItem item;

    JMenu file = new JMenu("File");
    menubar.add(file);

    item = new JMenuItem("New Game...");
    item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) { reset(); }
        });
    file.add(item);

    item = new JMenuItem("Save As...");
    item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) { saveGame(); }
        });
    file.add(item);

    item = new JMenuItem("Quit");
    item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) { quit(); }
        });
    file.add(item);
    JMenu gs = new JMenu("Game Settings");
    menubar.add(gs);

    item = new JMenuItem("Change Board");
    item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) { biggerBoard(); }
        });

    gs.add(item);
    item = new JMenuItem("Change Difficulty");
    item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) { changeDifficulty(); }
        });
    gs.add(item);  
}   

public void setx(int pmeter) {
    x = pmeter;
}

public void sety(int pmeter) {
    y = pmeter;
}

public int getx() {
    return x;
}

public int gety() {
    return y;
}

public void settried(boolean paramBoolean) {
    triedTrue = paramBoolean;
}

public boolean gettried() {
    return triedTrue;
}

public void setmine(boolean paramBoolean) {
    mineTrue = paramBoolean;
}

public boolean getmine() {
    return mineTrue;
}

//ASSIGN MINES TO RANDOM LOCATION
public void assignmines() {

    for(int row = 0; row < board.length; row++) {
        for(int col = 0; col < board[0].length; col++) {
            board[row][col] = 0;
        }
    }

    int minesPlaced = 0;
    Random t = new Random();
    while(minesPlaced < numberOfMines) {
        int row = t.nextInt(9);
        int col = t.nextInt(9);
        if(board[row][col] == Empty) {
            setmine(true);
            board[row][col] = Mine;
            minesPlaced++;
        }
    }

}


private void quit()
{
    System.exit(0);
}

//RESETS THE BOARD
public void reset()
{
    frame.setVisible(false);
    String tempName = GameBoard.this.namelabel.getText();
    frame.dispose();
    GameBoard gb= new GameBoard();
    gb.namelabel.setText(tempName);
    score = 0;
}    

public void newGame(){
    frame.setVisible(false);
    frame.dispose();
    new GameBoard();    
}

public void biggerBoard(){
    boardsize = 10; 
    reset();
}

public void changeDifficulty(){
    numberOfMines = 15;
    mine = 15;
    minesLeft  = 15;
    noMines.setText("Number of Mines: " + minesLeft);
    reset();
}

public void saveGame(){

    GameBoard b = new GameBoard();
    try {
        System.out.println("Creating File/Object output stream...");
        FileOutputStream fileOut = new FileOutputStream("mstate.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);

        System.out.println("Writing GameBoard Object...");
        out.writeObject(b);

        System.out.println("Save Successful...\n");
        out.close();
        fileOut.close();

    } catch(FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IO Exception!");
        e.printStackTrace();
    } 
}


public void loadBoard()throws IOException, ClassNotFoundException {
    GameBoard b = new GameBoard();
     try {
    System.out.println("Creating File/Object input stream...");

    FileInputStream fileIn = new FileInputStream("mstate.ser");
    ObjectInputStream in = new ObjectInputStream(fileIn);

    System.out.println("Loading GameBoard Object...");
    GameBoard obj = (GameBoard)in.readObject();


    System.out.println("Load Successful...\n");
   // in.close();
   // fileIn.close();
    b.setVisible(true);



     } catch(FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IO Exception!");
        e.printStackTrace();
    }
}


// LOSING THE GAME ALERT
public void lose() {

    status.setText("You're finished");
    gamegoing = false;
    JFrame parent = new JFrame();
    JOptionPane.showMessageDialog(parent, "Sorry, you lost");
    reset();
}

// WINNING THE GAME ALERT
public void win() {
    status.setText("You won!");
    gamegoing = false;
    JFrame parent = new JFrame();
    JOptionPane.showMessageDialog(parent, "Congratualations, you won!");
    updateGamesWon();
    GameBoard.this.setVisible(false);
    GameBoard.this.dispose();
    reset();   
}

// UPDATING THE SCORE
public void updatescore() {
    scorelabel.setText("" + score + " points");
    if (100 - score <= 10) win();

}

public void gamesPlayed() {
    gamesPlayed.setText("" + noGamesPlayed + " Games Played");

}

public void UpdateName() {  

    saveName.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                playername = nameEnter.getText();
                namelabel.setText(playername);

            }
        });
}

public void updateGamesPlayed() {
    noGamesPlayed ++;   
}

public void updateGamesWon() {
    noGamesWon ++;   
}

public void updateMinesLeft() {
    minesLeft --;   
    noMines.setText("Number of Mines: " + minesLeft);
}

//WHAT VALUES THE CHARACTER HAVE
static char whichCharacter(int value) {
    if(value == Mine) {
        return 'X';
    } else if( value == Empty) {
        return '+';
    } else if (value == Flag || value == FMine) {
        return 'F';
    } else if (value == RevealedMine) {
        return 'X';
    } else { String minesAround = Integer.toString(value);
        return minesAround.charAt(0);
    }

}
//This method shows how many mines are around the spot that was clicked
static int minesAround(int[][] board, int row, int col) {
    int numMines = 0;

    for(int i = -1; i <= 1; i ++) {
        for(int j = -1; j <= 1; j++) {
            if(row + i >= 0 && row + i < board.length &&
            col+ j >= 0 && col + j < board[0].length) {
                if(board[row+i][col+j] == Mine ||
                board[row+i][col+j] == FMine) {
                    numMines++;
                }
            }
        }
    }
    return numMines;
}

// This method takes in an x and y value and defines what should happen when the user clicks there. 
public void click(int rows, int cols) {
    if(board[rows][cols] == Mine) {
        buttons[rows][cols].setIcon( new ImageIcon( "images/bomb.gif" ) );
        updateMinesLeft();
        lose();
    } else {
        score += 1;
        updatescore();
        buttons[rows][cols].setText("" + minesAround(board, rows, cols));
        buttons[rows][cols].setForeground(Color.GREEN);
        board[rows][cols] = RevealedEmpty;
        if(minesAround(board, rows, cols) == Empty) {
            for(int i = 0; i <= 1; i ++) {
                for(int j = -1; j <= 1; j++) {
                    if(rows+i >= 1 && rows+i < boardsize &&
                    cols+j >= 1 && cols+j < boardsize) {
                        if(board[rows+i][cols+j] == Empty) {
                            click(rows+i,cols+j);
                        }
                    }
                }
            }
        }
    }
}

//ACTION WHEN USER CLICKS ON A BUTTON INNER CLASS
private class MouseListener extends MouseAdapter {
    private int x = 0;
    private int y = 0;

    public MouseListener(int row, int col) {
        this.x = row;
        int i = 0;
        this.y = col;
    }

    public void mouseClicked(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON1) {
            if((board[x][y] == Empty) && (GameBoard.this.gamegoing == true)) {
                GameBoard.this.click(x, y);
            } else if(board[x][y] == Mine) {
                buttons[x][y].setIcon( new ImageIcon( "images/bomb.gif" ) );
                GameBoard.this.lose();

            }} else if(e.getButton() == MouseEvent.BUTTON3) {
            GameBoard.this.buttons[x][y].setText("F");
        }
    }

}

}

有人可以帮助我退回游戏保存状态吗?

0 个答案:

没有答案