views:

76

answers:

3
some Function()
{  
    for(xxxxxx){
         //a infinite loop or just a long code loading an running stuff from a list
    }
}

ActionListener Panic(yyyyyyyy)
{
     Stops the infinite loop by list.clear() or insert some thing into the list and break the loop
}

I is trying to make a panic button to stop my code, problem is when Java is running some thing all the actionListener gets queued up and fires after my big for loop finish its stuff. This is probably a silly question but i can't seem to fig out. Only solution i can think of is making this a thread( kinda hard and not sure if it will work ) or give a pop up message ask if user want to continue every cycle( too much prompt ). Just want to have a Red button that either break the loop and destroy the program much like Ctrl Z in linux and red stop button in eclipse or the Cancel button that stops your file transfer.

Thanks for looking =D Lots and Lots of thanks

Oh btw, if the solution is Thread, please put it in the example i have above. I has almost no idea how to write a thread =(

+1  A: 

start your infinite loop in a new Thread.

org.life.java
A: 

The ultimate Java panic button implementation consists of a call to System.exit().

This will end the JVM process which means you need to be extra sure you want to exit this way as nothing will be cleaned up and any unfinished work will be left unfinished (think about database connections, transactions, in memory caches, etc.)

rsp
Mind you, people can add [shutdown hooks threads][1] to this System.exit. [1]: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)
Riduidel
Cool, thanks for the info
JavaLu
+2  A: 

If you want to stop an infinite (or very long) loop, the loop must regularly ensure if it has not been interrupted.

public class AlmostInfinite extends Thread {
    public void run() {
        while (!Thread.interrupted()) {
            /* Do some work, not too long */
        }
        cleanUp();
    }

    private cleanUp() {
        /* close network connections, files and other resources */
    }
}

ActionListener panic(AlmostInfinite t)
{
    t.interrupt();
}
Jcs
Awesome! Very good example and simple to understand =) Ty
JavaLu