Infinite while loop in init()

Can we have an infinite while loop in init() part of the applet?-Shilpa.
[86 byte] By [jainshilpaf] at [2007-9-30 20:19:18]
# 1

bad idea... it will never finish the loop

instead, you should have a thread, so the applet implements runnable (extends Applet implements Runnable) then you say in yor declarations :

Thread t //(or whatever else you wanna call it; loopThread, ect)

then in init, you say, assuming you used thread t:

init() {

t = new Thread(this);

t.start() //begins the thread

//then it calls the thread

later on, you use another method:

public void run() {

while(true) {

//whatever you wanna do

try {

t.sleep(30/1000 /*or whatever the delay you want it to be*/ ) ;

} catch(InterruptedException e) {

//whatever to do when the exception occures, propably nothing

}

}

}

here is a basic counting applet

import java.applet.*;

import java.awt.*;

public class Counter extends Applet implements Runnable {

Thread t;

int i;

public void init() {

t = new Thread(this);

t.start();

i = 0;

}

public void run() {

while (true) {

i++;

repaint();

try {

t.sleep(0);

} catch (InterruptedException e) { ; }

}

}

public void paint (Graphics g){

g.drawString ("i = "+i,50,20);

}

;}//the ; here is just cause the compiler complained...

hope this helps

Zebediah at 2007-7-7 1:04:19 > top of Java-index,Administration Tools,Sun Connection...