2012-08-14 6 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); 
} 
}}} 

나는 Tic Tac Toe Game에서 일하고있다. 현재 X와 O는 그냥 텍스트입니다. 그래서 버튼에 이미지 추가

for(int i=0; i<=8; i++) { 
    buttons[i] = new JButton(); 
    mainframe.add(buttons[i]); 
    buttons[i].addActionListener(this);} 

어떻게의 이미지를받을 수 있나요 ... 나는 이미지로 그들을 필요로하지만 모든 버튼 9 일 개 변수에에 '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

에서보세요