我正在用Java开发井字游戏,以自学Swing类。不过,我必须解决问题。
首先,如何使用图标比较按钮?
symX = new ImageIcon(this.getClass().getResource("symbolX.png"));
symO = new ImageIcon(this.getClass().getResource("symbolO.png"));
我使用这两个变量来设置按钮图像。
if (e.getSource() instanceof JButton) {
JButton source = (JButton) e.getSource();
if (isX) {
source.setIcon(symX);
source.setEnabled(false);
source.setDisabledIcon(symX);
} else {
source.setIcon(symO);
source.setEnabled(false);
source.setDisabledIcon(symO);
}
}
第二个问题是,您在哪里比较对象是动作事件?我试图比较上面代码中的if语句,但是Eclipse总是给我这样做的编译时错误。
如果我将代码放在带有按钮的方法中,似乎java永远都不会进入它们。
根据要求,这是我的Java文件的全部。
package ticTacToeGUI;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class tttGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9;
private ImageIcon symX, symO;
private ImageIcon symIco = new ImageIcon(this.getClass().getResource("symbolX.png"));
private boolean isX = true;
public static void main(String[] args) {
new tttGUI();
}
public tttGUI() {
//Setup the window.
super("Tic-Tac-Toe GUI 1.0");
setSize(425,425);
setIconImage(symIco.getImage());
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Create the content.
symX = new ImageIcon(this.getClass().getResource("symbolX.png"));
symO = new ImageIcon(this.getClass().getResource("symbolO.png"));
panel.setLayout(new GridLayout(3,3));
setVisible(true);
JButton btn1 = new JButton();
JButton btn2 = new JButton();
JButton btn3 = new JButton();
JButton btn4 = new JButton();
JButton btn5 = new JButton();
JButton btn6 = new JButton();
JButton btn7 = new JButton();
JButton btn8 = new JButton();
JButton btn9 = new JButton();
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
btn5.addActionListener(this);
btn6.addActionListener(this);
btn7.addActionListener(this);
btn8.addActionListener(this);
btn9.addActionListener(this);
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.add(btn6);
panel.add(btn7);
panel.add(btn8);
panel.add(btn9);
add(panel);
revalidate();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
JButton source = (JButton) e.getSource();
if (isX) {
source.setIcon(symX);
source.setEnabled(false);
source.setDisabledIcon(symX);
} else {
source.setIcon(symO);
source.setEnabled(false);
source.setDisabledIcon(symO);
}
}
isX ^= true;
}
}
最佳答案
我知道这已经太迟了两年,但是将来其他人可能会发现这很有用...
无论如何,巧合的是,我正在编程3D Tic Tac Toe。
为了比较ImageIcons
,我用String
描述初始化了图标,然后使用:
((ImageIcon) JLabel().getIcon()).getDescription().compareTo("someOtherDesc")
希望将来对您或其他人有帮助...