我有一个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 ....但它在执行循环后显示。问题是什么。请帮忙......
答案 0 :(得分: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();
答案 1 :(得分: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();
答案 2 :(得分: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();
}
}
答案 3 :(得分: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();
}