Finite Applet Thread Example

Before describing a threaded applet example, OneToTwenty is an applet that paints the numbers 1 to 20 in the applet window.

OneToTwenty

import java.applet.*;
import java.awt.Graphics;



public class OneToTwenty extends Applet
{

public void paint(Graphics g)
{
int i;
int xpos;
int ypos;

String text;
xpos = 0;
ypos = 50;



for (i=1; i<21; i++)
{
xpos = xpos + 20;
text = Integer.toString(i);
g.drawString(text, xpos, ypos);
}
}
}


This is a simple example of animation,

ThreadedNumbers

import java.applet.*;
import java.awt.Graphics;

public class ThreadedNumbers extends Applet implements Runnab le {
Thread numbersThread;
int xpos = 0;
int ypos = 0;
String text = '' ";

public void start()
{



}

public void run( ) {
int i;

xpos = 0;
ypos = 50;
for (i=1; i<21; i++)
{
try {
Thread.sleep(500);

} catch (InterruptedException e) {}
xpos = xpos + 20;
text = Integer.toString(i);
repaint();
}
}
public void paint(Graphics g)
{
g.drawString(text,xpos,ypos);
}
}

numbersThread = new Thread(this);
numbersThread.start();


Line 4 specifies in the applet class declaration that a Runnable interface is being implemented.

The start method (lines 10–13) overrides the applet class start method. In line 11, we pass an instance of the ThreadedNumbers class, this, as an argument to the Thread constructor. In line 12, the thread, numbersThread, is started.

Recall that starting a thread invokes the thread's run method. The run method (lines 15–28) includes a for loop that iterates over the numbers 1 to 20. For each iteration, we delay the thread's execution for half a second, 500 milliseconds, by means of the sleep method (line 22). In lines 24–25, we calculate the string equivalent, text, of the current iteration number and the horizontal position, xpos, of the number.

In line 26, we force the redrawing of the applet window by invoking the repaint method, which in turn, invokes the paint method. The thread is implicitly stopped as soon as the run method terminates.

No comments:

Post a Comment