To add an option for
ClockWidget
to have a different color, an instance must be obtained, instead of the hardcoded BLUE
reference. Since Color
objects are Resources
, they must be disposed correctly when the widget is disposed.
To avoid passing in a Color
directly, the constructor will be changed to take an RGB
value (which is three int
values), and use that to instantiate a Color
object to store for later. The lifetime of the Color
instance can be tied to the lifetime of ClockWidget
.
private final Color
instance called color
to ClockWidget
:private final Color color;
ClockWidget
to take an RGB
instance, and use it to instantiate a Color
object. Note that the color is leaked at this point, and will be fixed later:public ClockWidget(Composite parent, int style, RGB rgb) { super(parent, style); // FIXME color is leaked! this.color = new Color(parent.getDisplay(),rgb); ...
paintControl()
method to use this custom color:protected void paintControl(PaintEvent e) { ... e.gc.setBackground(color); e.gc.fillArc(e.x, e.y, e.width-1, e.height-1, arc-1, 2);
ClockView
to instantiate the three clocks with different colors:public void createPartControl(Composite parent) { ... final ClockWidget clock = new ClockWidget(parent, SWT.NONE, new RGB(255,0,0)); final ClockWidget clock2 = new ClockWidget(parent, SWT.NONE, new RGB(0,255,0)); final ClockWidget clock3 = new ClockWidget(parent, SWT.NONE, new RGB(0,0,255));
The Color
object was created based on the red/green/blue value passed in to the ClockWidget
constructor. Since RGB
is just a value object, it doesn't need to be disposed afterwards.
Once the Color
is created, it is assigned to the instance field. When the clocks are drawn, the second hands are the appropriate colors.