扫雷对象 GUI

Minesweeper Object GUI

我正在尝试使用 JFrame 做一个简单的扫雷游戏,但是我在创建对象时遇到了问题。我正在创建 96 个按钮,其中一些按钮得到 属性 错误 ("F") 和正确 ("R"):

public class GUIBase extends JFrame {

private JButton button;
private JButton fButton;


public GUIBase() {
    super("Minesweeper");
    setLayout(new FlowLayout());

    //Fields
    int position;
    for (int i = 0; i < 96; i++) {
        position = (int) (Math.random() * 100);
        if (position < 80) {
            button = new JButton("R");
            button.setToolTipText("Is this the correct one?");
            add(button);
        } else {
            fButton = new JButton("F");
            fButton.setToolTipText("Is this the correct one?");
            add(fButton);
        }           
    }

然后我使用ActionListener来检查按钮是否正确。如果按钮正确,则获得.setEnabled(false),否则游戏结束:

    //Action
    Action action = new Action();
    button.addActionListener(action);
    fButton.addActionListener(action);

}

private class Action implements ActionListener {

    public void actionPerformed(ActionEvent event) {
        System.out.println("Somethin");

        if (event.getSource() == button) {
            button.setEnabled(false);
        } else if (event.getSource() == fButton) {
            JOptionPane.showMessageDialog(null, "You lost!");
            System.exit(0);
        } else {
            JOptionPane.showMessageDialog(null, "An error ocurred");
            System.exit(0);
        }           
    }
} 

游戏中的一切都按计划进行,但是只有最后一个正确的按钮 ("R") 和最后一个错误的按钮 ("F") 连接到 ActionListener。其余按钮在按下时不执行任何操作。

我该如何解决这个问题?

问题是您只有两个变量(特别是 class GUIBase 的属性),并且每次您创建新按钮时都会分配给它。因此,您只能引用最后一个按钮。

您需要一组按钮。让我们看看:

public class GUIBase extends JFrame {
    public final int MAX_BUTTONS = 96;
    private JButton[] buttons;
// ...
}

下一步是在开头创建数组本身:

public GUIBase() {
    super("Minesweeper");
    setLayout(new FlowLayout());

    this.buttons = new JButton[MAX_BUTTONS];


    //Fields
    int position;
    for (int i = 0; i < buttons.length; i++) {
        position = (int) (Math.random() * 100);

        this.buttons[ i ] = new JButton("R");
        this.buttons[ i ].setToolTipText("Is this the correct one?");
        this.add(this.buttons[ i ]);

        Action action = new Action();
        this.buttons[ i ].addActionListener(action);
    }
}

您可能需要更深入地了解数组才能完全理解代码。基本上,一个数组是一个连续的变量集合,你可以通过它的位置索引,从 0 到 n-1,n 个位置。

那么您或许可以自己填补空白。

希望对您有所帮助。

您的部分问题来自您的动作侦听器。

当然,一方面是您的代码可能需要一个list/array来跟踪所有创建的按钮;但至少现在,您可以在不使用 arrays/list:

的情况下重新编写代码
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
    System.out.println("Somethin");
    if (event.getSource() instanceofJButton) {
       JBUtton clickedButton = (JButton) event.getSource();
       String buttonText = clickedButton.getText();
       if (buttonText.equals("R") ...
       else if (buttonText.equals("F")

你看,这里的重点是:到现在为止,你只需要知道创建了什么样的按钮。你的 ActionListener 知道它被点击的是哪个按钮...