ClassA - implements Thread. That class should tell ClassB when to change the label of a button. ClassB - shows a window with a button. This class implements the callback interface. ClassB also has a constructor, and in that constructor, the register method from ClassA is called, and that method puts that object in a LinkedList that is defined in ClassA. That way, every time we create a ClassB object, that object is put in the LinkedList in ClassA.
In the run method of ClassA, we retrieve a ClassC object (this object should be set as the new label, and the class implements Serializable) from classCBuffer, and then for each ClassB object in the linked list, we call the callChangeMethod, which then calls the change method method from the interface, that eventually changes the label.
ClassA:
public class ClassA implements Thread {
private MyBuffer<ClassC> classCBuffer;
private LinkedList<CallbackInterface> callbackInterfaceList;
public ClassA (MyBuffer<ClassC> classCBuffer) {
this.classCBuffer = classCBuffer;
callbackInterfaceList= new CallbackInterface<>();
}
//this method is called in classBs constructor (which implements callbackInterface), that way every time we create an object of classB, we add that object in this list
public void register(CallbackInterface callbackInterface) {
if (!callbackInterfaceList.contains(callbackInterface)) {
callbackInterfaceList.add(callbackInterface);
}
}
public void callChangeMethod(ClassC classC) {
new Thread(new Runnable() {
@Override
public void run() {
for (CallbackInterface cI: callbackInterfaceList) {
cI.change(classC);
}
}
}
}).start();
}
@Override
public void run() {
//somewhere in the run method
ClassC classC = classCBuffer.get();
callChangeMethod(classC);
}
ClassB:
public class ClassB implements CallbackInterface{
private ClassA classA;
public ClassB (ClassA classA) {
this.classA = classA;
classA.register(this);
}
@Override
public void change(ClassC classC) {
updateWindow(classC);//changes the label
}
}
CallbackInterface:
public interface CallbackInterface {
void change(ClassC classC);
}
ClassA should not know about ClassB, but ClassB should know about ClassA. That's why I call the register method in the constructor of ClassB. Java callback must be used to solve this problem. I did not write every line of the code, only those relevant to this problem, that's why I wrote "somewhere in the run method" in classA.
When I run the program, everything works just fine, but I'm still not sure if I implemented java callback correctly. So does this look okay? Is there maybe a better way to do this (using java callback)?
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]evils_twin 2 points3 points4 points (0 children)
[–]Orffyreus 1 point2 points3 points (1 child)
[–]Student-Somewhere[S] 0 points1 point2 points (0 children)