[英]How can I keep updating a JLabel in ActionListener?
GUI中有兩個按鈕:“開始”和“停止”。 還有一個JLabel“ trainInfoDetail”。 單擊“開始”時,如何在“停止”按鈕仍在偵聽並且始終真正終止循環的情況下每秒讓JLabel中的“速度”更新一次? 我的程序在循環時似乎在此循環中堆疊並禁用“停止”按鈕,直到完成為止。
myButton1 = new JButton("Go!",icon1);
myButton2 = new JButton("Stop!",icon2);
HandlerClass onClick = new HandlerClass();
myButton1.addActionListener(onClick);
myButton2.addActionListener(onClick);
private class HandlerClass implements ActionListener{
//overwriting
public void actionPerformed(ActionEvent event){
long startTime = System.currentTimeMillis();
long now;
String caller = event.getActionCommand();
if(caller.equals("Go!")){
while(speed < 100){
now = System.currentTimeMillis();
if((now - startTime) >= 1000){
speed += 10;
trainInfoDetail.setText("Speed: "+speed+" mph");
startTime = now;
}
}
}
else if (caller.equals("Stop!")){
speed = 0;
trainInfoDetail.setText("Speed: "+speed+" mph");
}
}
}
使用Timer之后:
public class HandlerClass implements ActionListener{
//overwriting
public void actionPerformed(ActionEvent event){
String caller = event.getActionCommand();
TimeClass tc = new TimeClass(caller);
timer = new Timer(1000, tc);
timer.setInitialDelay(1000);
timer.start();
}
}
public class TimeClass implements ActionListener{
String caller;
public TimeClass(String caller){
this.caller=caller;
}
//overwriting
public void actionPerformed(ActionEvent event){
if(caller.equals("Go!")){
speed += 10;
trainInfoDetail.setText("Speed: "+speed+" mph");
}
else if (caller.equals("Stop!")){
timer.stop();
}
else{
timer.stop();
//return;
}
}
}
簡短的答案,使用Swing Timer
。 有關更多詳細信息,請參見如何使用Swing計時器 。
基本上,您可以將Timer
設置為每隔一秒(或您需要的間隔)滴答並安全地更新狀態/變量和UI,而不會阻塞UI或不違反Swing的線程規則,並且可以在“停止”位置停止Timer
只需通過調用Timer
的stop
方法即可單擊按鈕
您還應該看看Swing中的並發性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.