0
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);}

では、「O」の画像を取得するにはどうすればよいですか? if(count % 2 == 0)?

4

1 に答える 1

3
Icon icon = null;
if(count % 2 == 0)
{
    icon = iconThatIsO;
}
else
{
    icon = iconThatIsX;
}

JButton pressedButton = (JButton)source;
pressedButton.setIcon(icon);

アイコンの使い方を見てみる

于 2012-08-14T01:53:34.033 に答える