Domanda

I'm making a tic tac toe game in java for individual learning purposes, and I'm trying to change the text of the button from "-" to "O" when the button is clicked. Obviously I'm not going about it correctly and some tips would be greatly appreciated.

When I run the code I also get the error "at java.awt.AWTEventMulticaster.mouseEntered(Unknown Source)"

//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();
            }
        }
    });

}       
È stato utile?

Soluzione

What you want to do is to set up a listener at the beginning, of the program, not on a call to playerMove. So something like this

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.
}

Of course you probably would want to use a loop rather than repeating similar code 9 times, but, as you say, that's another issue.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top