0

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

    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();
        }
    });

}

}

4

1 回答 1

1

您也许可以采用这个简单游戏中使用的方法。它使用具有实例的JPanel命名。当用户改变游戏的大小时,调用buttonPanelGridLayoutJToggleButtonActionListenerresetGame()

buttonPanel.validate();
于 2013-04-04T08:46:31.510 回答