Reputation: 5648
Sorry for my confusing title, but i don't know any better.
I have two classes:
The first class (called MainClass
) create a GUI that contain a Socket. When any data is received from Socket Class, onReceived()
will be called. So in this onReceived()
method, i want a way to send a message back to the MainClass
so that MainClass
can know position has change and call setPostion()
.
So what is the properly way to do this (if necessary, correct my model for better practice). Thanks
Upvotes: 1
Views: 198
Reputation: 2456
You can do the following;
Define listener interface:
public interface MyListener(){
public void doNotify(String message);
}
The Socket class (has a methot to add listeners that are notified on onRecieve()):
public class SocketClass {
private List<MyListener> listeners = new ArrayList<MyListener>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
public void onRecieve(){
/* your code*/
for (MyListener l : listeners)
l.doNotify("Socket has recieved something ;P");
}
}
The Gui class has a method that passes on the listener:
public class GuiClass() {
SocketClass s = new SocketClass();
public void addListener(MyListener listener) {
s.addListener(listener);
}
}
And finally the main class (implements the listener interface and adds itselef to GuiClass as listener):
public class MainClass implements MyListener {
public static void main(String[] args)
{
GuiClass g = new GuiClass();
g.addListener(this);
}
public void doNotify(String message) {
System.out.println(message);
setPostition();
}
private void setPosition()
/* your code here */
}
}
A good example is also THIS.
Good luck and Regards
Upvotes: 1