Application -> Custom Canvas Now that we can trigger events on the custom canvas, we may also want to build a way of controlling the custom canvas from the broader application. For this example, I am going to use a Choice component that allows you to choose a colour. When you choose the colour, all of the items in the custom canvas will change to that colour (red, green and blue). The source code of the custom canvas needs to change slightly. I have renamed it to CustomCanvasControl and I have added in a method called setColor() that allows you to pass a Color object from the application to the canvas. Once you pass this Color object, the custom canvas redraws itself with the circles in their new colour. Everything else stays largely the same, except that I now have to share the Color object between the methods, so I have added a Color state called drawColor that allows the Color object to be shared between the setColor() method and the paint() method.
The source code of the application needs to change to include the Choice component. I have called this component colorChoice and set it as a state of the class, so that it can be shared between the constructor and the itemStateChanged() method. This class now needs to implement the ItemListener interface as this is the way that we trap events that occur when you choose one of the colours in the Choice component. This requires us to write a method itemStateChanged() that is called when the chosen item changes. The Choice component is listening for events thanks to the line colorChoice.addItemListener(this) in the constructor.
That is the way that we have worked with components so far, and is no different than calling a method on an object after we have created it. These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way. |