Using thread to dynamically display system time
- 2020-04-01 04:14:05
- OfStack
Write an Applet Applet that displays the current system time in different colors and fonts by receiving parameters in an HTML document.
import java.awt.*;
import java.applet.Applet;
import java.util.*;
import java.awt.Graphics;
public class clock extends Applet implements Runnable //Inherit the Applet class and implement the Runnable interface
{
Thread clockThread=null; //Create an empty thread
Calendar now;
private String s1;
private int size;
int r1,g1,b1;
public void init() //Initialization method
{
size=Integer.parseInt(getParameter("size"));//Get font size
}
public void start()
{
if(clockThread==null)
{
clockThread=new Thread(this,"Clock2"); //Create the thread object clockThread
clockThread.start(); //Start thread
}
}
public void run() //Implement the run() method of the Runnable interface
{
Thread myThread=Thread.currentThread();//Create a thread object called myThread
while(clockThread==myThread) { repaint(); //The paint method is called through the repaint method
try
{
Thread.sleep(1000); //Dormancy of 1 second
}
catch (InterruptedException e){}
}
}
public void paint(Graphics g)
{
r1=(int)(Math.random()*255); //Generates a random number by calling random of the Math class
g1=(int)(Math.random()*255); //Then through the random number to set the three primary colors, red, green and blue
b1=(int)(Math.random()*255);
Color c=new Color(r1,g1,b1); //Create a color object
g.setColor(c); //Set the color
now=Calendar.getInstance(); //Gets the current system time
s1=now.get(now.HOUR)+" when "
+now.get(now.MINUTE)+" points "
+now.get(now.SECOND)+" seconds ";
Font f=new Font("",1,size); //Set the font
g.setFont(f);
g.drawString(s1,10,50); //Displays a string with the specified size and color
}
public void stop() //Call the stop method to stop the thread
{
clockThread=null;
}
}
<pre class="html" name="code"><html>
<Applet code="clock.class" width=300 height=100>
<param name=s1 value=s1>
<param name=size value=30>
</Applet>
</html></pre><br>
<pre></pre>
<p> </p>
<pre></pre>
<div style="padding-top:20px">
<p style="font-size:12px;"> Using thread to dynamically display system time </p>
</div>
This is how to use thread to dynamically display the system time method, hope to help you learn.