【发布时间】:2015-08-29 21:48:04
【问题描述】:
所以我对 java 比较陌生(自学成才,所以我喜欢你能给的任何建议/批评),作为练习,我决定创建一个使用 Jbuttons 作为 Dice 的摇摆骰子滚动程序。为了模拟掷骰子,我想在呈现结果之前将 Jbutton 的文本随机更改为不同的数字几秒钟。
在我尝试从 ActionPerformed 方法中调用 if 之前,我为此编写的方法似乎有效。当我这样做时,程序将冻结直到方法结束,然后将按钮文本更改为最终结果。
我很好奇是否有人可以解释为什么会发生这种情况,或者教我正确的方法来做这样的事情。感谢您的帮助。
下面是同一问题的一个简单示例
package experiments.changingtext;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ChangingText extends JFrame implements ActionListener{
JButton button = new JButton("Change Me");
public ChangingText(){
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
button.addActionListener(this);
pane.add(button);
this.add(pane);
this.setVisible(true);
try{Thread.sleep(500);}catch(Exception ex){}
//Works as expected
this.changeButtonText();
}
@Override
public void actionPerformed(ActionEvent e) {
//when run program freezes and presents the final text "change to 5"
if(e.getSource() == button){
button.setText("change to 1");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 2");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 3");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 4");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 5");
}
}
public void changeButtonText(){
button.setText("change to 1");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 2");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 3");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 4");
try{Thread.sleep(500);}catch(Exception ex){}
button.setText("change to 5");
}
}
【问题讨论】:
-
Swing 使用单线程来管理事件和绘制,这意味着我们使用 Thread.sleep,你阻塞了事件调度线程,阻止它绘制 ui。相反,您可以使用 Swing Timer
标签: java swing jbutton action dice