java - JButton 数组到 int 数组

标签 java arrays swing int jbutton

我正在尝试用java swing制作一个Tic Tac Toe程序,并且我已经制作了框架。我怎样才能让 JButton 数组中的按钮激活 int 数组?我希望 int 数组保存 Tic Tac Toe 网格中点的值,因此当按下按钮时,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);
    }

}

最佳答案

您可以创建自己的 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

关于java - JButton 数组到 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641061/

相关文章:

arrays - SwiftUI 复选标记单行

javascript - 无法仅过滤数组的唯一值

java - 将 Action 监听器添加到 RadioPanel

java - CentOS 上 Apache FOP 中的字体无限扫描

java - 从用户生成的多维数组输出数据

ios - Swift 中的数组扩展,使用 NSPropertyListReadOptions 从 plist 读取数组

java - 使用 java DefaultCellEditor 在 JTable 中获取正确的编辑行为

java - 如何从 JTextPane 中删除组件

java - 在我的 jsp 页面上包含 jsp 文件时出错

JavaFX 显示可缩放 vector 图形?