我正在尝试用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/