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