Source of DigitalClockGUIApp.java


  1: //DigitalClockGUIApp.java

  3: import java.awt.*;
  4: import javax.swing.*;
  5: import java.util.*;

  7: public class DigitalClockGUIApp extends JFrame
  8: {
  9:     WatchPanel watch = new WatchPanel();

 11:     public DigitalClockGUIApp()
 12:     {
 13:         super("Digital Clock");
 14:         setSize(400, 60);
 15:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 16:         JPanel pane = new JPanel();
 17:         pane.setLayout(new GridLayout(1, 1, 15, 15));
 18:         pane.add(watch);
 19:         setContentPane(pane);
 20:         show();
 21:     }

 23:     public static void main(String[] arguments)
 24:     {
 25:         DigitalClockGUIApp clock = new DigitalClockGUIApp();
 26:     }
 27: }

 29: class WatchPanel extends JPanel
 30: implements Runnable
 31: {
 32:     Thread runner;

 34:     WatchPanel()
 35:     {
 36:         if (runner == null)
 37:         {
 38:             runner = new Thread(this);
 39:             runner.start();
 40:         }
 41:     }

 43:     public void run()
 44:     {
 45:         while (true)
 46:         {
 47:             repaint();
 48:             try
 49:             {
 50:                 Thread.sleep(1000);
 51:             }
 52:             catch (InterruptedException e)
 53:             {
 54:             }
 55:         }
 56:     }
 57: 
 58:     public void paintComponent(Graphics comp)
 59:     {
 60:         Graphics2D comp2D = (Graphics2D)comp;
 61:         Font type = new Font("Serif", Font.BOLD, 24);
 62:         comp2D.setFont(type);
 63:         comp2D.setColor(getBackground());
 64:         comp2D.fillRect(0, 0, getSize().width, getSize().height);
 65:         GregorianCalendar day = new GregorianCalendar();
 66:         String time = day.getTime().toString();
 67:         comp2D.setColor(Color.black);
 68:         comp2D.drawString(time, 5, 25);
 69:     }
 70: }