Click to See Complete Forum and Search --> : Loop breaks Java Applet!


sythem
07-30-2007, 02:08 PM
Hello everyone,
Here's my problem, I put a loop in my applet and the applet just sits at the loading applet screen. Nothing happens, I take out the Menu();, and it works fine. With the exception of course that Menu function won't repeat. Any ideas?public void Menu()
{
buffer.setColor(Color.green);
buffer.drawString("Double-buffered",20,20);
repaint();
try { Thread.sleep(20);} catch (InterruptedException e) {}
Menu();
}
I also tried public void Menu()
{
while(stillon == 1)
{
buffer.setColor(Color.green);
buffer.drawString("Double-buffered",20,20);
repaint();
try { Thread.sleep(20);} catch (InterruptedException e) {}
}
}
But this makes no difference. I'm so confused and a little annoyed.

Declan1991
08-04-2007, 05:50 PM
Wouldn't it be easier to call Menu() from a while(true){} loop?

agent_x91
08-16-2007, 03:12 PM
What method is Menu() first called from? Your problem appears to be that you're entering a never-ending loop before you allow the applet to load...

Your best bet here would probably be to multi-thread your applet if all else fails.


By the way, I disagree with declan, but you'd be better off using a boolean as the condition to keep the loop up, rather than checking if an integer is equal to 1. You only need true/false, so a boolean is your best bet.

eg.



boolean stop_running=false;


while(!stop_running)
{
//...
}


Also, putting the method call within the while loop is a much better idea than putting the loop within the method.

Declan1991
08-16-2007, 07:30 PM
Also, putting the method call within the while loop is a much better idea than putting the loop within the method.

Do you mean that he should use

public static void Menu () {
boolean stop_running=false;
while(!stop_running) {
//...
}
}

or

while (true) {
Menu();
}


I'm interested to know because I don't have much Java experience.

agent_x91
08-17-2007, 06:39 AM
A cross between the two:


protected boolean stop_running=false;

public void stopRunning()
{
stop_running=true;
}
public boolean isRunning()
{
return !stop_running;
}

public void run()
{
//or whatever method Menu() is being run from

while(!stop_running)
Menu();

stop_running=false;
}


You could then stop the main run loop running at any point by calling stopRunning(), and you could add other methods than the Main() loop whenever necessary.

It may be necessary to multithread the application to get it to work the way he wants it to though.