将图像添加到按钮

时间:2012-08-14 01:47:19

标签: java image swing icons jbutton

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游戏。目前,The X's And O's Are Just Text。我需要它们作为图像,但所有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)?

1 个答案:

答案 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