2014-04-25 116 views
2

为了个人学习目的,我正在制作一个tic tac toe游戏,当我点击按钮时,我试图将按钮的文本从“ - ”更改为“O”。很显然,我没有正确地解决这个问题,并且我将不胜感激。Tic Tac Toe游戏

当我运行的代码我也得到了错误“在java.awt.AWTEventMulticaster.mouseEntered(来源不明)”

//includes graphics, button, and frame 
import java.awt.*; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

import javax.swing.*; 


public static JButton [][] b = new JButton[3][3]; 

public static void playerMove(){ 
b[0][0].addMouseListener(new MouseAdapter() { 
     public void mouseClicked(MouseEvent e) { 
      String text = b[0][0].getText(); 
      if(text.equals("-")){ 
       b[0][0].setText("O"); 
       //computerMove(); 
      } 
      else{ 
       System.out.println("Pick Again"); 
       playerMove(); 
      } 
     } 
    }); 

}  
+0

你总是看着'b [0] [0]'。你需要弄清楚如何得到被点击的特定按钮的索引... – pennstatephil

+1

我建议你使用'ActionListener'而不是'MouseListener'。 –

+0

这是一个完全不同的问题。我只是想能够现在点击该特定按钮b [0] [0]并且改变文本。 – user3574427

回答

2

你想要做的是建立一个监听之初,的程序,而不是致电playerMove。因此,像这样

public static JButton [][] b = new JButton[3][3]; 
{ // Initialization code follows 
    b[0][0].addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      String text = b[0][0].getText(); 
      if(text.equals("-")){ 
       b[0][0].setText("O"); 
       computerMove(); 
      } 
      else{ 
       System.out.println("Pick Again"); 
      } } }); 
    // And so on for the other 8 buttons. 
} 

当然,你可能会想使用一个循环,而不是重复类似的代码9倍,但是,就像你说的,那是另一个问题。

+0

更改为actionlistener而不是mouselistener结束了工作。谢谢! – user3574427