2012-08-14 183 views
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」,如果......如果(計數%2 = = 0)?

回答

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

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

看看How to Use Icons