Difference between revisions of "Have an on-screen clock"

From CodeCodex

(Java)
 
(Implementations)
Line 94: Line 94:
 
</highlightsyntax>
 
</highlightsyntax>
 
Try it [http://www.rgagnon.com/examples/myclock.html here. ]
 
Try it [http://www.rgagnon.com/examples/myclock.html here. ]
 +
 +
=== Tcl ===
 +
<pre class="tcl">
 +
proc every {t script} {
 +
eval $script
 +
after $t [list every $t $script]
 +
}
 +
pack [label .horloge -textvariable time -font {Lucida 18}]
 +
every 1000 {set ::time [clock format [clock seconds] -format %H:%M:%S]}
 +
</pre>
 +
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Tcl]]

Revision as of 20:28, 3 March 2011

Implementations

Java

<highlightsyntax language="java122"> import java.applet.*; import java.awt.*; import java.util.*; import java.text.*;

public class MyClock extends Applet {

 MyPanel mp;
 public void init() {
   mp = new MyPanel(getParameter("format"));
   add(mp);
   }
 }

class MyPanel extends Panel {

 MyClockThread mct;
 Color b, f;
 SimpleDateFormat formatter;
 String previousDateText = "";
 String dateText;
 MyPanel(String df) {
   super();
   formatter = new SimpleDateFormat(df);
   validate();
   setBackground(new Color(0).black);
   setForeground(new Color(0).yellow);
   b = this.getBackground();
   f = this.getForeground();
   mct = new MyClockThread(this);
   mct.start();
   }
 public Dimension getPreferredSize() {
   return new Dimension
    (this.getFontMetrics(this.getFont()).stringWidth(getNow()) + 25, 30);
   }
 public void paint(Graphics g) {
   if (g != null) {
      g.setColor(b);
      g.drawString(previousDateText,10,15);
      g.setColor(f);
      dateText = getNow();
      g.drawString(dateText,10,15);
      previousDateText = dateText;
      }
   }
 public String getNow() {
   return formatter.format(new Date());
   }

}

class MyClockThread extends Thread {

 MyPanel mp;
 public MyClockThread(MyPanel a) {
   mp = a;
   }
public void run() {
  while (true) {
    try {
      mp.repaint();
      this.sleep(1000);
      }
    catch(InterruptedException e) { }
    }
  }

} </highlightsyntax> <highlightsyntax language="java122"> <HTML><HEAD></HEAD><BODY> <APPLET CODE="MyClock.class"

       HEIGHT=25 WIDTH=200>

<PARAM NAME="format" VALUE="yyyy-MM-dd hh:mm:ss">

</APPLET>

<APPLET CODE="MyClock.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="h:mm a"> </APPLET><P> <APPLET CODE="MyClock.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="yyyy.MMMMM.dd GGG hh:mm aaa"> </APPLET><P> <APPLET CODE="MyClock.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="H:mm:ss:SSS"> </APPLET><P> </BODY></HTML> </highlightsyntax> Try it here.

Tcl

proc every {t script} {
 eval $script
 after $t [list every $t $script]
}
pack [label .horloge -textvariable time -font {Lucida 18}]
every 1000 {set ::time [clock format [clock seconds] -format %H:%M:%S]}