Skip to Content

Create Number counter in an Applet using Thread Example

  1. /*
  2.         Create Number counter in an Applet using Thread Example
  3.         This Java example shows how to create number counter using Java Thread and
  4.         Applet classes.
  5. */
  6.  
  7.  
  8. import java.applet.Applet;
  9. import java.awt.Dimension;
  10. import java.awt.Font;
  11. import java.awt.FontMetrics;
  12. import java.awt.Graphics;
  13.  
  14. /*
  15. <applet code = "UsingRepaintAndThreadExample" width = 500 height = 300>
  16. </applet>
  17. */
  18.  
  19. /*
  20.         Using paint() method we can draw strings, shapes or images.
  21.         But when applets that use threads commonly need to update the display
  22.         (ex. Animation or simulation).
  23.        
  24.         You cannot invoke the paint method directly to update the display.
  25.         The reason is that the JVM schedules a number of important tasks. Updating
  26.         the dispaly is one of these. The JVM decides when the screen can be updated.
  27.        
  28.         Therefore, your applet must invoke the repaint() method to request
  29.         an update of the applet display. When the JVM determines that it is
  30.         appropriate to perform this work, it calls the update method.
  31.        
  32.         The default implementation of the update() method clears the applet
  33.         display with the background color and then invokes the paint() method.
  34. */     
  35.  
  36. public class UsingRepaintAndThreadExample extends Applet implements Runnable{
  37.         int counter;
  38.         Thread t;
  39.        
  40.         public void init(){
  41.                
  42.                 counter = 0;
  43.                 t = new Thread(this);
  44.                 t.start();
  45.         }
  46.        
  47.         public void run(){
  48.                
  49.                 try{
  50.                        
  51.                         while(true){
  52.                                 repaint();
  53.                                 Thread.sleep(1000);
  54.                                 ++counter;
  55.                         }
  56.                 }
  57.                 catch(Exception e){
  58.                 }
  59.         }
  60.        
  61.         public void paint(Graphics g){
  62.                
  63.                 g.setFont(new Font("Serif",Font.BOLD,30));
  64.                 FontMetrics fm = g.getFontMetrics();
  65.                 String s = "" + counter;
  66.                 Dimension d = getSize();
  67.                 int x = d.width/2 - fm.stringWidth(s)/2;
  68.                 int y = d.height/2;
  69.                 g.drawString(s,x,y);
  70.         }
  71. }