Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class design: change text on button click

I have 2 classes for the game I am making: a gui class and the logic class, for a game of noughts and crosses. The GUI class has a method that uses an array of JButtons and returns them all with the same anonymous inner class action listener.

When I click the button, I want the text to change to an x or a o dependant on player 1 or 2 go, but this code should be in the logic class shouldn't it so somehow I should be making a method in the logic class and calling it from the anon inner class action listener of the make button method. However, the logic class shouldn't have a reference to the gui, as the gui has a reference to the logic class.


1 Answers

Consider the following sketch of classes:

public class Game{
    public void switchPlayer(){
        // among other things calls all GameListeners
    }
    public void setMarker(int x, int y);

    public Player getCurrentPlayer();
    public Player getPlayerOwningField(int x, int y);

    public void registerGameListener(GameListener l);
}

public interface GameListener(){
    void gameChanged(Game g)
}

public class GUI implements GameListener(){
    private Game game;
}

When a field is clicked, game.setMarker(x,y) is called. The game know who the current Player is, so it can mark the field apropriately. It will also fire a GameChanged event. During setup of the application the gui must get registered / register itself as a GameListener to the game. So it will get informed as well. It uses the getters of the game to update the gui. Done.

Of course there is plenty of room for refinement, e.g. in a large game it wouldn't be a good idea to update the complete UI just because one field got change, but it should get you started

like image 120
Jens Schauder Avatar answered Dec 08 '25 07:12

Jens Schauder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!