Ajay Sainy
Ajay Sainy

Reputation: 379

ConfirmDialog of JOptionPane in Java

I have a JLabel and a JButton. In the following code I am trying to change the JLabel text on button click before the for loop executes, but the JLabel text changes after the loop executes. Here is the code-

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        int n = JOptionPane.showConfirmDialog(null, "Print??");
        if(n==JOptionPane.YES_OPTION)
                {
                    jLabel1.setText("Please Wait...");
                    System.out.println("Hello");

                    for(int i = 0 ; i<65000;i++)
                    {
                        System.out.println("printing");
                    }

                }
    }    

However Hello is printed before the loop execution. I am doing something else in for loop, that also takes some time, till the loop executes I want to show Please Wait... . But it is displayed after the execution of loop. What is the problem. Please Help...

Upvotes: 0

Views: 141

Answers (4)

Prasad
Prasad

Reputation: 1188

Thread t1 = new Thread() {
            public void run() {
            lbl.setText("Please wait...");
            pnl.updateUI();
        }
    };
    Thread t2 = new Thread() {

        public void run() {
            for (int i = 0; i < 10000; i++) {
                pnl.updateUI();
                System.out.println("Printing");
            }
            lbl.setText("Done!!!");
        }
    };

Declare this globally and on clicking of the button write t1.start() and t2.start();

Upvotes: 1

Mohsin AR
Mohsin AR

Reputation: 3108

this is just because when method completes its execution after that its changed button text so you should use thread concept as jogi said..

public class YouClass implements Runnable {

public void run() {
   // set text here 
}

public void run() {
   // use loop here  
}

public static void main(String args[]) {
    (new Thread(new YouClass())).start();
    (new Thread(new YouClass())).start();
}

}

Upvotes: 0

Sharma
Sharma

Reputation: 24

if (n == JOptionPane.YES_OPTION) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                jLabel1.setText("Please Wait...");
                System.out.println("Hello");
                for (int i = 0; i < 65000; i++) {
                    System.out.println("printing");
                }
                jLabel1.setText("Done...");
            }
        }).start();
    }

Upvotes: 0

shreyansh jogi
shreyansh jogi

Reputation: 2102

It is better if you use Thread concept in this issue.

**EDIT**

Thread thread1 = new Thread () {
  public void run () {
//   set your label code here 
  }
};
Thread thread2 = new Thread () {
  public void run () {
    // iterate your loop here 
  }
};
thread1.start();
thread2.start();

Upvotes: 0

Related Questions