Java Thread In Applet


 

Java Thread In Applet

In this segment of tutorial we will learn how to use the Thread in the Applet.Then We will create an example and use the Thread with Applet.

In this segment of tutorial we will learn how to use the Thread in the Applet.Then We will create an example and use the Thread with Applet.

  • Java Thread Applet is a java class that runs inside the internet browser.
  • It is used to make the gui application, network application in java
  • Thread is used in applet to make the multithread application

Example of Java Thread in Applet

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Color;
import java.util.Date;

//<applet code="Clock" width="100" height="100"></applet>
public class Clock extends java.applet.Applet implements Runnable {
private Thread clockThread = null;

public void init() {
setBackground(Color.white);
}

public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}

public void run() {
Thread myThread = Thread.currentThread();
while (clockThread == myThread) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void paint(Graphics g) {
setBackground(Color.CYAN);
Font f = new Font("serif", Font.BOLD, 25);
g.setFont(f);
Date now = new Date();
g.drawString(now.getHours() + ":" + now.getMinutes() + ":"
+ now.getSeconds(), 5, 30);
}

public void stop() {
clockThread = null;
}
}

Ads