【发布时间】:2017-04-24 04:39:09
【问题描述】:
我正在创建一个简单的井字游戏。我使用 [3][3] 矩阵创建了 9 个 JButton。问题是我需要检查这些按钮的状态,以便确定获胜者。
我不知道如何在没有某种标识符或索引的情况下通过 if 语句检查/访问这些按钮。我可以创建 9 个 JButton 对象并使用 if 语句检查它们,但它似乎效率不高。 我知道这不是这个游戏的最佳解决方案,我应该为游戏逻辑创建一个完整的类,但是这种方式似乎非常有效,我真的很想知道如何做到这一点。
代码如下:
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.GridLayout;
public class AdinTicTacToe extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500; //Width of the JFrame
public static final int HEIGHT = 400; //Height of the JFrame
public static void main(String[] args) {
AdinTicTacToe gui = new AdinTicTacToe(3, 3);
gui.setVisible(true);
}
//Creating a matrix of buttons to make flexible layout
JButton[][] buttons = new JButton[3][3];
{
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons[0].length; col++) {
JButton cells = new JButton();
buttons[row][col] = cells;
add(cells);
cells.addActionListener(this);
}
}
}
//A constructor to set initial values
public AdinTicTacToe(int rows, int columns) {
super();
setSize(WIDTH, HEIGHT);
setTitle("Tic Tac Toe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting a layout
setLayout(new GridLayout(rows, columns));
}
//Handling button clicks
boolean check; //Variable to determine the current state of a button
@Override
public void actionPerformed(ActionEvent e) {
//Using getSource method to avoid multiple if statements and make it efficient
JButton myButton = (JButton) e.getSource();
if (!check)
myButton.setText("X");
; //Set X to the clicked cell
if (check)
myButton.setText("O"); //Set O to the clicked cell
check = !check; //Reverting the button state
myButton.setFont(new Font("Arial", Font.BOLD, 60)); //Set font of X and O
myButton.setEnabled(false); //Disable button after it gets clicked
}
}
【问题讨论】:
-
你想在哪里查看他们的
state? -
我想在 actionPerform 方法中使用 if 语句来检查它,但我没有这些按钮的索引。
-
为什么需要索引?什么不工作?
-
我需要在有人获胜时显示消息。我需要检查是否有三个XXX在同一行、同一列或同一对角线
-
啊。我知道了。好吧,请稍等
标签: java swing multidimensional-array