0

我正在尝试使用 java swing 制作一个井字游戏程序,并且我已经制作了框架。如何使 JButton 数组中的按钮激活 int 数组?我希望 int 数组保存井字游戏网格中点的值,因此当按下按钮时,int 数组中的对应点将为 0 或 1,并且按钮的文本将更改为一个 X 或一个 O。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class TicTacToeGui extends javax.swing.JFrame implements ActionListener
{

    int[][] grid = new int[3][3];
    public final static int r = 3;
    public final static int c = 3;
    public final static int X = 0;
    public final static int O = 1;

    TicTacToeGui()
    {
        this.setTitle("Tic Tac Toe");
        JButton[][] button = new JButton[3][3];
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(r, c));
        for(int i = 0; i < r; i++)
        {
            for(int j = 0; j < c; j++)
            {
                button[i][j] = new JButton("");
                button[i][j].addActionListener(this);
                panel.add(button[i][j]);
            }

        }
        this.add(panel);
        this.setSize(400, 400);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e){
        if(e.getSource() instanceof JButton){

        }
    }
    public static void main(String [] args)
    {
        new TicTacToeGui().setVisible(true);
    }

}
4

3 回答 3

2

您可以创建自己的JButton实现并向其提供索引值。我们可以从ActionListener

public void actionPerformed(ActionEvent e){
    if(e.getSource() instanceof MySuperButton){

        MySuperButton btn = (MySuperButton)e.getSource();
        int[] index = btn.getIndex();
        // or
        int row = btn.getRow();
        int col = btn.getColumn();

    }
}

然后,当您设置它时,您可以:

for(int i = 0; i < r; i++)
{
    for(int j = 0; j < c; j++)
    {
        button[i][j] = new MySuperButton(i, j); // Store the row/column
        button[i][j].addActionListener(this);
        panel.add(button[i][j]);
    }

}

这也将允许您在内部存储按钮的状态......

您可能还想看看JToggleButton

于 2012-07-25T00:28:49.783 回答
0

假设 JButton 索引镜像 int 数组,您可以在按钮数组中搜索被按下的 JButton ( e.getSource()in actionPerformed),但您必须将按钮数组作为类的实例变量,以便您可以从其他方法使用它,尤其是。actionPerformed(). _ 找到索引后,只需在 int 数组中更新它的对应值。

于 2012-07-25T00:23:07.580 回答
0

使用 JButton 的 setActionCommand 方法将 button[0][0] 中的动作命令设置为“00”,将 button[2][1] 中的命令设置为“21”。这让你很容易从 actionPerformed 中获得职位。此外,您需要三个状态,而不仅仅是 2 个。如果您不确定我在说什么,请玩井字游戏并在中途写下数组。

于 2012-07-25T00:36:45.077 回答