Write an Applet applet to display the current system time in different colors and fonts by receiving parameters in the 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 the font size} public void start() { if(clockThread==null) { clockThread=new Thread(this,"Clock2"); //Create a thread Object clockThread clockThread.start(); //Start executing the thread} } public void run() //Implement the run() method of the Runnable interface { Thread myThread=Thread.currentThread();//Create the thread object myThread while(clockThread==myThread) { repaint(); //Call the paint method through the repaint method try { Thread.sleep(1000); //Sleep for 1 second} catch (InterruptedException e){} } } public void paint(Graphics g) { r1=(int)(Math.random()*255); //Generate a random number g1=(int)(Math.random()*255) by calling the random number of the Math class; //Then set the three primary colors respectively through random numbers, 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(); //Get the current system time s1=now.get(now.HOUR)+"hour" +now.get(now.MINUTE)+"minute" +now.get(now.SECOND)+"second"; Font f= new Font("",1,size); //Set the font g.setFont(f); g.drawString(s1,10,50); //Display a string of specified size and color} public void stop() // Call the stop method to stop the thread { clockThread=null; } } <pre 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;">Use threads to dynamically display system time</p> </div>
This is how to use threads to dynamically display system time. I hope it will be helpful to everyone's learning.