Nikhil
Nikhil

Reputation: 2883

how to suspend execution in java using thread

i have created a wizard programatically. it contain 3 panels. the second one is devicePane and third one is detailsPane. the third panel consist of a progress bar. i want my program to start a function process() after displaying the third panel? is it possible using thread?

else if(ParserMainDlg.this.POSITION==1){
    if(sqlConnectionPane.executeProcess()==true){    
        devicePane.setDeviceList();                             
         ParserMainDlg.this.POSITION++;
         fireStateChanged(oldValue);
    }
}
else if(ParserMainDlg.this.POSITION==2){
    System.out.println("position:"+ParserMainDlg.this.POSITION);
    if(devicePane.executeProcess()==true){
         ParserMainDlg.this.POSITION++;
         fireStateChanged(oldValue);    
    }

I want sqlConnectionPane.executeProcess() to call a function which starts executing after displaying the devicePane Panel?

Upvotes: 0

Views: 324

Answers (1)

Maarten Blokker
Maarten Blokker

Reputation: 604

You can definitly use a thread to execute your task, this is the preferred way of handling a long running task.

You have multiple options here. All options include making a callback to your wizard, to update the progressbar.

You can make your own task class wich does exactly this, or you can use the existing SwingWorker. "SwingWorker itself is an abstract class; you must define a subclass in order to create a SwingWorker object; anonymous inner classes are often useful for creating very simple SwingWorker objects."

Using the swing worker we just learned about you can use something like this:

SwingWorker<Integer, Integer> backgroundWork = new SwingWorker<Integer, Integer>() {

        @Override
        protected final Integer doInBackground() throws Exception {
            for (int i = 0; i < 61; i++) {
                Thread.sleep(1000);
                this.publish(i);
            }

            return 60;
        }

        @Override
        protected final void process(final List<Integer> chunks) {
            progressBar.setValue(chunks.get(0));
        }

    };

    backgroundWork.execute();

Note that you will have to break your task down into smaller parts to actually be able to display progress.

Upvotes: 1

Related Questions