0

I'm writing simple Peer-Server-Peer chat application in Swing. On the client side, there is a 'Client' object responsible for Client-Server communication and 'MainWindow' which is a main jForm.

Upon receiving a message, 'Client' needs to notify the 'MainWindow' about the new message. However, 'MainWindow' is an object created at the start of the program (in my case after the 'Client' is created), so I'm looking for a way of passing 'MainWindow' reference to 'Client'.

I was thinking about creating 'Resource' class with static references to objects I need to communicate with within my app, but it doesn't seem very elegant.

Is there a better way to do this?

4

2 回答 2

0

Have a look at Guava's EventBus. You can use it to communicate between the two classes without them having references to each other.

于 2013-05-30T11:10:56.380 回答
0
public interface MessageListener {
    public void notify(Message msg);
}

public class MainWindow implements MessageListener {
    public void notify(Message msg) {
        // UI Action
    }
}

public class Client {
    private MessageListener listener;

    public void setMessageListener(MessageListener listener) {
        this.listener = listener;
    }
}

You can use something similar to Publish Subscribe Pattern where MainWindow Subscribes to Publisher Client and from client whenever you get a message can call listener.notify method. Thus the notify method in MainWindow will be called.

于 2013-05-30T11:13:57.130 回答