【发布时间】:2014-06-19 14:25:31
【问题描述】:
我创建了一个基本的井字游戏类,它显示了 9 个按钮,上面显示了随机图像(每个运行时间 - 不同的序列)。主要方法在另一个测试类中,它只是一个框架创建者。除此之外,我还想添加一些事件处理。我已将“ActionListener”添加到按钮中,并希望在“actionPerformed”方法中添加一些逻辑。每次我单击任何按钮时,它都应该按照 X -> O -> 空白 -> X 的顺序连续更改图像。我不确定哪种逻辑适合此处以上述顺序翻转图像(例如 for-loop、switch等等。)。代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToe extends JFrame {
public JButton[][] labels = new JButton[3][3];
public ImageIcon[] icons = new ImageIcon[3];
public int r, c;
public TicTacToe() {
// TODO Auto-generated constructor stub
setLayout(new GridLayout(3, 3));
for (r = 0; r < labels.length; r++) {
for (c = 0; c < labels.length; c++) {
int random = (int)(Math.random() * 3 + 0);
System.out.println(random);
JButton s = new JButton(this.icons[random]);
this.add(s);
this.labels[r][c] = s;
if (random == 0) {
System.out.println("Cross Image Icon");
labels[r][c].setIcon(new ImageIcon("C:\\Users\\yogesh\\workspace\\hw3pandarey\\src\\hw3pandarey\\cross_symbol.gif"));
add(labels[r][c]);
validate();
} else if (random == 1) {
System.out.println("Not Image Icon");
labels[r][c].setIcon(new ImageIcon("C:\\Users\\yogesh\\workspace\\hw3pandarey\\src\\hw3pandarey\\zero_symbol.gif"));
add(labels[r][c]);
validate();
} else if (random == 2) {
System.out.println("Keep it blank");
labels[r][c].setIcon(new ImageIcon());
add(labels[r][c]);
validate();
}
labels[r][c].addActionListener(new ButtonListener());
}
}
} // end of TicTacToe constructor
public class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
} // end of actionPerformed method
} // end of ButtonListener class
} // end of TicTacToe class
import javax.swing.*;
public class TicTacToeTest {
public static void main(String[] args) {
TicTacToe frame = new TicTacToe();
frame.setTitle("Let's play a random tic-tac-toe game !!!!!");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} //end of main method
} // end of test class
【问题讨论】:
标签: java swing awt jbutton imageicon