package net.tictacsnow.src;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tictacsnow implements ActionListener {
private int[][] winCombinations = new int[][] {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
{0, 4, 8}, {2, 4, 6} //diagonal wins
};
private JButton buttons[] = new JButton[9];
static int width = 480;
static int height = 640;
private static JFrame congrats = new JFrame("Winner");
private int count = 0;
static private String letter = "";
private static JFrame mainframe = new JFrame();
static String x = "X";
static String y = "Y";
public static void main(String[] args) {
tictacsnow snow = new tictacsnow();
snow.go();
}
public void go() {
congrats.setSize(240, 320);
mainframe.setSize(width, height);
mainframe.setLocationRelativeTo(null);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setLayout(new GridLayout(3,3));
mainframe.setVisible(true);
for(int i=0; i<=8; i++) {
buttons[i] = new JButton();
mainframe.add(buttons[i]);
buttons[i].addActionListener(this);}
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
count++;
if(count % 2 == 0)
{
letter = "O";
}
else
{
letter = "X";
}
JButton pressedButton = (JButton)source;
pressedButton.setText(letter);
pressedButton.setEnabled(false);
for(int i=0; i<=7; i++)
{
if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i] [1]].getText()) &&
buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
buttons[winCombinations[i][0]].getText() != "")
{
congrats.setVisible(true);
}
}}}
我正在开发井字游戏。目前,X 和 O 只是文本。我需要它们是图像,但所有 9 个按钮都在 1 个变量中......
for(int i=0; i<=8; i++) {
buttons[i] = new JButton();
mainframe.add(buttons[i]);
buttons[i].addActionListener(this);}
那么,当... if(count % 2 == 0) 时,我如何获得“O”的图像?