官术网_书友最值得收藏!

Time for action – getting colorful

To add an option for the ClockWidget to have a different color, an instance must be obtained instead of the hardcoded BLUE reference. Since Color objects are Resource objects, 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 the ClockWidget.

  1. Add a private final Color field called color to the ClockWidget:
    private final Color color;
  2. Modify the constructor of the 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);
      ...
  3. Modify the drawClock method to use this custom color:
    protected void drawClock(PaintEvent e) {
      ...
      e.gc.setBackground(color);
      e.gc.fillArc(e.x, e.y, e.width-1, e.height-1, arc-1, 2);
  4. Finally, change the 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));
  5. Now run the application and see the new colors in use:

What just happened?

The Color was created based on the red, green, blue value passed into the ClockWidget constructor. Since the RGB is just a value object (it isn't a Resource), 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 in the appropriate colors.

Note

One problem with this approach is that the Color instance is leaked. When the view is disposed, the associated Color instance is garbage-collected, but the resources associated with the native handle are not.

主站蜘蛛池模板: 陆良县| 镇原县| 镇雄县| 易门县| 浙江省| 泰州市| 彩票| 新田县| 高淳县| 波密县| 鄢陵县| 肥乡县| 荥经县| 新绛县| 正阳县| 墨竹工卡县| 盘锦市| 洛宁县| 黔西县| 和龙市| 南华县| 德安县| 韶山市| 睢宁县| 嘉善县| 沭阳县| 吴江市| 杨浦区| 临安市| 乌海市| 龙井市| 呼伦贝尔市| 铜鼓县| 巢湖市| 民权县| 烟台市| 静海县| 芒康县| 虞城县| 古交市| 双流县|