我想用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