Custom Canvas -> Application
So, we have written code to allow our application to modify the state/properties of the custom canvas by calling its methods. The question now is how do we do it the other way? In our application, every time you press the button you create a new circle -- what if we wanted to tell the application how many circles had been created? This is a form of callback, as the application has no idea when a new circle will be created, so we need to pass that information from the custom canvas back to the application.
In the figure below you can see the number of circles displayed in the read-only TextField.
Figure X. Canvas Application with Callback
The application needs to be modified slightly as we now need to pass a reference of the application to the custom canvas. You can see that below - when we create the custom canvas we use this.canvas = new CustomCanvasCallback(this, 250, 250); so we are passing a reference to this object (the application) to the constructor of the CustomCanvas, which has been modified to receive the reference.
We also add a new method in the application called setNumberCircles(int) that allows us to pass the message from the custom canvas to the application. This method simply places the the number in the TextField object called numberCircles.
The custom canvas object has been modified below to now receive a reference to the calling application in the constructor, so you can see "CanvasApplicationCallback app" being passed to the canvas object. Now that we have this reference (called callingApp), we are now able to call the setNumberCircles(int) method. So, when we redraw the canvas we can send a message back to the application to tell it to update the text in the TextField (even if it doesn't need to be updated).