我正在尝试编写tic-tac-toe。我希望当我点击它时按钮变为“X”。
我的代码并没有完全完成。
但我希望看到按钮改变文字。但我没有看到任何变化
的setText();方法看起来对我来说。 :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tictac extends JFrame implements ActionListener{
JButton [][] game = new JButton[3][3];
JLabel head = new JLabel("Tic-Tac-Toe");
Font font = new Font("Time New Roman", Font.ITALIC, 20);
GridLayout grid = new GridLayout(3,3,0,0);
int row,column =0;
FlowLayout flow = new FlowLayout();
tictac(){
//setLayout(flow);
//add(head);
super("Tic-Tac-Toe");
setLayout(grid);
setVisible(true);
setDefaultCloseOperation(1);
setSize(500,500);
for (row =0; row<3;row++ ){
for(column =0; column <3;column++){
game[row][column]= new JButton("");
add(game[row][column]);
game[row][column].addActionListener(this);
}
}
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source == game[row][column])
game[row][column].setText("X");
System.out.println("X");
}
}
我做错了什么?
答案 0 :(得分:3)
您错误地使用了row
和column
当您创建这些JButton时,这些值已在您的double for循环中更新(现在都是3)
当您在actionPerformed
中再次访问它们时,一个问题是它会导致ArrayIndexOutOfBoundsException。
注意:这只是一个快速修复 将行数(ROWS)和列数(COLS)声明为常量 执行操作时,使用双循环检查每个按钮。
<强>代码:强>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QuickTester {
public static void main (String [] args) {
TicTac tt = new TicTac();
}
}
class TicTac extends JFrame implements ActionListener{
JButton [][] game = new JButton[3][3];
JLabel head = new JLabel("Tic-Tac-Toe");
Font font = new Font("Time New Roman", Font.ITALIC, 20);
GridLayout grid = new GridLayout(3,3,0,0);
FlowLayout flow = new FlowLayout();
static final int ROWS = 3;
static final int COLS = 3;
TicTac(){
//setLayout(flow);
//add(head);
super("Tic-Tac-Toe");
setLayout(grid);
setVisible(true);
setDefaultCloseOperation(1);
setSize(500,500);
for (int row = 0; row < ROWS; row++ ){
for(int col = 0; col < COLS; col++){
game[row][col]= new JButton("");
add(game[row][col]);
game[row][col].addActionListener(this);
}
}
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
for(int row = 0; row < ROWS; row++) {
for(int col = 0; col < COLS; col++) {
if (source == game[row][col])
game[row][col].setText("X");
System.out.println("X");
}
}
}
}
<强>输出:强>