0

我有一个 JLabel 和一个 JButton。在下面的代码中,我试图在 for 循环执行之前更改按钮单击时的 JLabel 文本,但循环执行后 JLabel 文本会更改。这是代码-

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");
                    }

                }
    }    

然而 Hello 在循环执行之前被打印出来。我正在 for 循环中做其他事情,这也需要一些时间,直到循环执行我想显示 Please Wait... 。但它是在循环执行后显示的。问题是什么。请帮忙...

4

4 回答 4

1
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!!!");
        }
    };

全局声明这一点并单击按钮写入t1.start()t2.start();

于 2013-10-10T12:26:42.227 回答
0
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();
    }
于 2013-10-10T12:20:57.890 回答
0
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();
于 2013-10-10T12:10:57.310 回答
0

这只是因为当方法完成它的执行之后,它改变了按钮文本,所以你应该使用 jogi 说的线程概念..

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();
}

}
于 2013-10-10T12:16:00.587 回答