带有GUI的MineSweeper,如何更改字段的大小然后刷新JFrame?

时间:2013-04-03 20:18:52

标签: java swing user-interface jframe jdialog

我正在尝试用GUI进行扫雷游戏,当我添加一个人们可以改变场地大小和地雷数量的菜单时,我无法改变JFrame。如果玩家向JTextBox输入内容并按下JDialog上的提交按钮,我想更改按钮和地雷的数量。基本上我想在 MineSweeper 类中更改sizeX,sizeY,mines变量,然后用新值刷新帧。

    public class MineSweeper {
private static int sizeX=20;
private static int sizeY=20;
private static int mines=20;

private static JFrame frame;

public static void setX(int x){
    sizeX = x;
}
public static void setY(int y){
    sizeY = y;
}
public static void setM(int m){
    mines = m;
}
public static void refreshFrame(){
    frame.validate();
    frame.repaint();
}

public static void main(String[] args){

    frame = new JFrame("");
    frame.setTitle("MineSweeper Game");
    frame.setBackground(Color.white);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menu = new JMenuBar();
    JMenu options = new JMenu("Options");
    JMenuItem gameProperties = new JMenuItem("Game Properties");
    menuHandler menuHandling = new menuHandler();
    gameProperties.addActionListener(menuHandling);
    options.add(gameProperties);
    menu.add(options);
    frame.setJMenuBar(menu);
    frame.setSize(sizeX*sizeY, sizeX*sizeY);
    if(gameProperties.isEnabled()) frame.validate();
    frame.add(new MineSweeperGUI(sizeX, sizeY, mines));
    frame.setVisible(true);

}

}

class menuHandler implements ActionListener{
JDialog dialog;
JButton button;
JPanel panel;
JLabel sizeRow, sizeCols, mineCount;
JTextField sizeX, sizeY, mines;
int  x, y, m;
public menuHandler(){
    dialog = new JDialog();
    dialog.setSize(400,120);
    panel = new JPanel(new GridLayout(4, 2));
    sizeRow = new JLabel("Row size of the field: ");
    sizeCols = new JLabel("Column size of the field: ");
    mineCount = new JLabel("Number of mines: ");
    sizeX = new JTextField(10);
    sizeY = new JTextField(10);
    mines = new JTextField(10);
    panel.add(sizeRow);
    panel.add(sizeX);
    panel.add(sizeCols);
    panel.add(sizeY);
    panel.add(mineCount);
    panel.add(mines);
    button = new JButton("Submit");
    panel.add(button);
    dialog.add(panel);
}

public void actionPerformed(ActionEvent e) {
    dialog.setVisible(true);

    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            String sizeofRows = sizeX.getText();
            String sizeofCols = sizeY.getText();
            String countofMines = mines.getText();
            MineSweeper.setX(Integer.parseInt(sizeofRows));
            MineSweeper.setY(Integer.parseInt(sizeofCols));
            MineSweeper.setM(Integer.parseInt(countofMines));
            MineSweeper.refreshFrame();
            dialog.dispose();
        }
    });

}

}

1 个答案:

答案 0 :(得分:1)

您可以采用此简单game中使用的方法。它使用名为JPanel的{​​{1}} buttonPanelGridLayout个实例。当用户更改游戏大小时,JToggleButton会调用ActionListener

resetGame()