我想用swing写一个Tic Tac Toe程序,但是我似乎遇到了一些麻烦。在我的匿名内部类中,我尝试为每个按钮设置actionListener,但是我无法找到允许我引用按钮并将它们设置为X或Y的类型或变量。我尝试了e .getSource()。setText()在我的匿名类中,但返回错误。有什么想法吗? 谢谢! 亚历在ActionListener里面引用点击JButton
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe {
public JFrame frame;
public JLabel label;
public JPanel panel;
public static int counter;
public void go()
{
frame = new JFrame("TicTacToe");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridLayout(3,3,10,10));
frame.add(BorderLayout.CENTER, panel);
label= new JLabel("TIC TAC TOE");
frame.add(BorderLayout.NORTH, label);
;
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 1");
JButton button3 = new JButton("Button 1");
JButton button4 = new JButton("Button 1");
JButton button5 = new JButton("Button 1");
JButton button6 = new JButton("Button 1");
JButton button7 = new JButton("Button 1");
JButton button8 = new JButton("Button 1");
JButton button9 = new JButton("Button 1");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
panel.add(button7);
panel.add(button8);
panel.add(button9);
frame.setVisible(true);
panel.setVisible(true);
}
public static void main(String[] args)
{
TicTacToe gui = new TicTacToe();
gui.go();
}
}
非常感谢。我真的很感激这种帮助,而且这也创造了奇迹。 – Amloelxer
另一个问题。以这种方式确定赢家的最佳方式是什么?假设我做了一个计数器并且有((JButton)源).setText(“O”);或((JButton)源).setText(“X”); – Amloelxer
其实,最好的办法是建立某种模型。这将允许您检查游戏状态并确定选择哪些单元格以及由谁选择。每次玩家选择一个按钮,我都会更新模型。这个过程的一部分是为模型检查一个胜利者并且引发一个适当的事件 – MadProgrammer