Build a Customizable Java Analog Clock with Swing

Build a Customizable Java Analog Clock with Swing

Overview

This tutorial shows how to build an analog clock in Java using Swing, with customization options for size, colors, tick marks, and smooth vs. discrete hand movement. The clock uses a JPanel for drawing (override paintComponent), a javax.swing.Timer for animation, and basic trigonometry to position hands.

Key components

  • JFrame — container for the clock.
  • ClockPanel (extends JPanel) — handles drawing and resizing.
  • Timer — updates the display every 16–1000 ms depending on smoothness.
  • Configuration object or setters — expose size, face color, hour/minute/second hand colors, tick style, and movement mode.

Core implementation steps

  1. Create a JFrame and add an instance of ClockPanel.
  2. In ClockPanel, override paintComponent(Graphics g); cast to Graphics2D and enable anti-aliasing.
  3. Compute center (cx, cy) and radius based on current panel size for responsive resizing.
  4. Draw clock face: fill circle for background, draw border.
  5. Draw tick marks: loop 60 steps, use trigonometry (angle = Math.toRadians(i6)) to compute inner/outer points; draw longer ticks for hours.
  6. Compute hand angles:
    • Hour angle = 30hour + 0.5minute + (0.⁄60)*second (for smooth hour hand).
    • Minute angle = 6minute + 0.1second.
    • Second angle = 6*second + (smooth ? fractionalMillis * 0.006 : 0). Convert to radians and subtract Math.PI/2 to start at 12 o’clock.
  7. Draw hands with different lengths and stroke widths; optionally add rounded caps and shadows.
  8. Use a javax.swing.Timer:
    • For discrete second ticks: 1000 ms.
    • For smooth second hand: 16–50 ms (approx 60–20 FPS). Timer action calls repaint().
  9. Expose customization via constructor parameters or setter methods and call revalidate()/repaint() on changes.
  10. Handle high-DPI and scaling by deriving strokes from radius.

Example code sketch

java

// See full implementation in your editor; key idea: Timer timer = new Timer(smooth ? 16 : 1000, e -> repaint()); timer.start();

Customization ideas

  • Themes (light/dark), gradient face, numerals or minimalist ticks.
  • Enable/disable second hand; add date or timezone hands.
  • Smooth interpolation for minute/hour hands when smooth seconds enabled.
  • Click-and-drag to reposition or resize; save presets.

Performance & polish tips

  • Minimize object creation in paintComponent (reuse Shapes).
  • Use RenderingHints for quality.
  • Respect Swing thread rules (create UI on EDT).
  • Provide accessible font sizes and color-contrast themes.

If you want, I can provide a complete ready-to-run Java class implementing this with all customization options—tell me which options you want (size, colors, smooth movement).

Comments

Leave a Reply