
You can definitely take advantage of the area operations GraphicsBuilder already provides but you can also create a shape operation and register it with a GraphicsBuilder instance, as a matter of fact, that is how the previous image was created, here is the relevant code for setting the builder
Notice that donuts are registered through a factory, thanks to the facilities provided by FactoryBuilderSupport and extended by GraphicsBuilder itself. So how is the Donut shape made then? a shape operation must implement
ShapeProvider
, Transformable
, take care of filling and drawing the shape, fire events whenever any of its properties changes value, etc. Fortunately you don't have to start from scratch, there is a convenient AbstractShapeGraphicsOperation
class that does the heavy lifting for you, leaving the job of actually creating the shape to your class. Because the donut is computed as an area operation and we do not want to compute that area again and again we are going to cache the resulting shape, but allow for it to be recomputed if any of the donut's properties changes. Here is the Donut classAlright, lets step into the code
- Donut extends AbstractShapeGraphicsOperation, already explained
- the static
required
property signals the superclass for special treatment of any property that matches those names, specially when firing events. - the
shape
field will hold the cached donut. - now we see the actual properties, defined with
def
as to make it easier for binding, and with some default values in case some of them are not defined at runtime. - the constructor defines the name of the new operation, useful for debugging.
getShape
is the single method Donut must implement to provide the shape, here you can see that the cached shape is used if not null, computed otherwise and returned.- here is an interesting bit, each shape registers itself as PropertyChangeListener, so if it receives a PropertyChangeEvent the cached shape is set to null.
- what its left is to create the actual donut shape, done with a
subtract
area operation on two circles.
Groovy Holidays!