2017-03-16 55 views
0

我正在製作一個tic tac toe遊戲,並且如何讓這個按鈕只有一個特定的字母。當點擊一個按鈕時,它會轉到x,但一旦再次按下,它會轉到o。我如何製作它,以便它被固定,並且一旦按下它就不會變形?如何使按鈕不被點擊?

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 

public class TicTacToeSample extends JFrame implements ActionListener 
{ 
    private JFrame game = new JFrame("TicTacToe"); 
    private JButton button1 = new JButton(""); 
    private JButton button2 = new JButton(""); 
    private JButton button3 = new JButton(""); 
    private JButton button4 = new JButton(""); 
    private JButton button5 = new JButton("");    
    private JButton button6 = new JButton(""); 
    private JButton button7 = new JButton(""); 
    private JButton button8 = new JButton(""); 
    private JButton button9 = new JButton(""); 
    private String letter = "X"; 
    private int count = 0; 
    private boolean win = false; 

    public TicTacToeSample() 
    { 
     game.setSize(300,300); 
     game.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     game.setLayout(new GridLayout(3, 3)); 

     game.add(button1); 
     game.add(button2); 
     game.add(button3); 
     game.add(button4); 
     game.add(button5); 
     game.add(button6); 
     game.add(button7); 
     game.add(button8); 
     game.add(button9); 


     button1.addActionListener(this); 
     button2.addActionListener(this); 
     button3.addActionListener(this); 
     button4.addActionListener(this); 
     button5.addActionListener(this); 
     button6.addActionListener(this); 
     button7.addActionListener(this); 
     button8.addActionListener(this); 
     button9.addActionListener(this); 

     game.setVisible(true); 
    } 


     public void actionPerformed(ActionEvent event) 
     { 
      count++; 

      if (count == 1 || count == 3 || count == 5 || count == 7 || count == 1) 
      { 
       letter = "X"; 
      } 
      else if (count == 2 || count == 4 || count == 6 || count == 8 || count == 10) 
      { 
       letter = "O"; 
      } 

      if(event.getSource()== button1) 
      { 
      button1.setText(letter); 
      } 
      if(event.getSource()== button2) 
      { 
      button2.setText(letter); 
      } 
     } 




     public static void main(String[] paramArrayOfString) 
     { 
     TicTacToeSample board = new TicTacToeSample(); 
     } 
} 
+0

刪除動作監聽器 – ControlAltDel

+0

禁用按鈕 – MadProgrammer

回答

2

在ActionListener中,通過在ActionEvent參數上調用getSource()來獲得按下的按鈕。檢查它的文本,如果有任何呼籲getText()就可以了。如果有文字,請勿更改。簡單。