2

I have java method that executes a very long model. It takes about 20 minutes. When I press the button, the button remains pressed until the model is finished. I need to create a button that when is pressed, it stop the model execution So far I have 2 buttons: Stop and Start. My problem is that when I press the start button, all the buttons from the GUI are freeze and they cannot be pressed until the model finishes

How can I create a stop button?

Thank you,

Ionut

4 Answers4

3

You should use a SwingWorker. They are specifically designed for performing long running tasks off of the EDT while still being able to update the GUI with progress reports.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
2

It is best to start a Thread once the button is clicked. You could make a stop button that stops the thread if it has not finished yet. For this you will have to keep track of the Thread though (for example in a static variable).

A quick guide to threading: http://www.tutorialspoint.com/java/java_multithreading.htm

Please take a look at this as well: How to properly stop the Thread in Java?.

Community
  • 1
  • 1
bas
  • 1,678
  • 12
  • 23
0

If you are executing a 20 minute task in response to a button click you should probably be doing it in a background thread.

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
0

You have to use multi-threading. A basic example-

public class ThreadTest {

    private int getSum(int x, int y){
        return x + y;
    }

    public static void main(String args[]) {

        ThreadTest tTest = new ThreadTest();        
        System.out.println(tTest.getSum(2, 5));
        // Start the thread
        new LongProcess().start();        
        // Since the thread sleeps for two seconds
        // You will see 5 + 5 = 10 before Done! gets printed out
        System.out.println(tTest.getSum(5, 5));

    }
}

class LongProcess extends Thread {

    public LongProcess(){
        System.out.println("Thread started.."); 
    }

    public void run() {
        try{                   
            Thread.sleep(2000);
            System.out.println("Done!");        
        } catch(InterruptedException iEx){
            System.out.println(iEx.toString());        
        }
    }
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74