views:

164

answers:

1

i have written a standalone connect 4 game.

next i would like to be able to play it over network and also have a chat function.

connect 4 GUI (JFrame) holds -> connect 4 game model

i would like to implement connect 4 network GUI(JDialog) (here the user can choose to act as a server or client) that holds Network API. (server only serving a single connection)

and finally a Chat GUI (JDialog) to exchange messages.

my question is how do i implement inter class/GUI communication? when a network message is received it ought to be delivered to the right receiver (game / chat) also messages sent from chat / game transmitted to remote machine.

i have looked into inner classes but was told it is a bad idea to implement so much with in single class and i did not like this idea a lot either.

i have written another game battleships in C# and it uses delegates to accomplish this task but sadly im informed that delegates are not available in Java.

im a beginner and at the moment exploring options so im open to your guidance.

thank you.

+1  A: 

There are two issues here.

First, you must remember that all GUI operation must be issued from the Swing's Event Dispatching Thread (EDT). So, if another thread (such as the thread listening to network messages) want to update the GUI it must use SwingUtilities.invokeLater as follows:

 // Network thread
 final Message msg = getMessage();
 SwingUtilities.invokeLater(new Runnable() {
   public void run() {
      // This code will be executed on the EDT
      // it can access the msg variable because it is final
   }
 });

The second point is that of coordinating the GUI objects and networking objects. I think the best approach is to create two Mediator classes that will receive notifications from the networking object and "translate" them into appropriate action on the GUI object (and vice versa). These mediators will also make sure that GUI events are dispatched on the EDT, as explained above.

Itay
This is a super ingenious way to implement what I would like! It shows integrity in the code without passing entire objects around. Very neat! Thank you a lot for presenting this idea.
iEisenhower