Time for action – drawing a seconds hand

A clock with no hands and no numbers is just a circle. To change this, a second hand will be drawn using a filled arc.

Since arcs are drawn anticlockwise from 0 (on the right, or 3 o'clock) through 90 degrees (12 o'clock), then 180 degrees (9 o'clock), then 270 degrees (6 o'clock), and finally back to 360 degrees (3 o'clock), it is possible to calculate the arc's position for the second hand using the expression (15 – seconds) * 6 % 360.

  1. Go to the drawClock method of the ClockView class.
  2. Add a variable called seconds that is initialized to LocalTime.now().getSecond().
  3. Get the SWT.COLOR_BLUE via the display, and store it in a local variable, blue.
  4. Set the background color of the graphics context to blue.
  5. Draw an arc using the formula mentioned earlier to draw the second hand.
  6. The code should look like this:
    public void paintControl(PaintEvent e) {
      e.gc.drawArc(e.x, e.y, e.width-1, e.height-1, 0, 360);
      int seconds = LocalTime.now().getSecond();
      int arc = (15 - seconds) * 6 % 360;
      Color blue = e.display.getSystemColor(SWT.COLOR_BLUE);
      e.gc.setBackground(blue);
      e.gc.fillArc(e.x, e.y, e.width-1, e.height-1, arc-1, 2);
    }

    Tip

    Make sure that org.eclipse.swt.graphics.Color is used rather than the same-named classes from java.awt.

  7. Start Eclipse and show the Clock View. The second hand will be shown once but won't change.
  8. Resize the view. Then the second hand will be drawn in the new location:
    Time for action – drawing a seconds hand

What just happened?

The code calculates the position on the arc at which the second hand will need to be drawn. Since the arc degrees go anticlockwise, the seconds have to be negative. The offset of 15 represents the fact that an arc of 0 is at the 3 o'clock position, which is 15 seconds. This is then multiplied by 6 (60 seconds = 360 degrees) and finally the result is calculated modulus 360, to ensure that it's up to 360 degrees (the value can be negative; the arc calculation works in this way as well).

Although drawArc colors in the foreground color, the fillArc colors in the background color. The GC maintains two colors; a foreground color and a background color. Normally an SWT Color object needs to have a dispose after use, but to simplify this example, the Display class's getSystemColor method is used, whose result does not need to be disposed.

Finally, the arc is drawn 2 degrees wide. To center it, the arc starts from pos-1, so it is drawn from pos-1 to pos+1.

When the view is resized, a redraw is issued on the canvas, and so the second hand is drawn in the correct position. However, to be useful as a clock, this should be done automatically do this while the view is visible.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.17.46