开发者

How to send events simply in Java?

开发者 https://www.devze.com 2023-01-02 20:20 出处:网络
I\'m writing a basic tic tac toe game in Java. In my Board class I have a swing window which determines which button was p开发者_Python百科ressed.

I'm writing a basic tic tac toe game in Java. In my Board class I have a swing window which determines which button was p开发者_Python百科ressed. TttGame is the class which has a Board object.

The goal of this board is not to act as a fully functional tic-tac-toe board but to serve as a framework where the TttGame class controls all the logic. As such I need the Board to send some kind of event when the button is pressed to the TttGame class with the id of the button that has been pressed.

What is the simplest method of doing this?

edit: I found something called the Observer pattern - Is this the simplest method of doing this?


Yes, the Observer pattern is what you want to apply here. Create a Listener interface (BoardListener) perhaps like this:

public interface BoardListener {
    public void squareSelected(int x, int y);
}

Then maintain a Set or List of listeners in your Board class and cycle through them, calling squareSelected on each, when a square is chosen.

I would look into the Model-View-Controller pattern however, in which the View listens to the Model for changes, and the Controller detects user actions and changes the model accordingly.


I would suggest altering your design a bit. Having the game logic and keeping track of piece locations on the board can all be done in an "engine"(or a series of classes without a visual display).

You would then have an intermediate class for communicating all the piece locations to an interchangeable display class. It could also handle any communication from the display class to the engine(such as clicking to place an X or O)

P.S. I was thinking of checkers, not tic tac toe when typing this up, but the design is still applicable

0

精彩评论

暂无评论...
验证码 换一张
取 消