如何在 ActionListener 中不断更新 JLabel?

How can I keep updating a JLabel in ActionListener?

GUI 中有两个按钮:"Go" 和 "Stop"。还有一个 JLabel "trainInfoDetail"。单击 "Go" 时,如何让 JLabel 中的 "speed" 每秒更新一次,而 "Stop" 按钮仍在监听并始终真正终止循环?我的程序在循环时似乎堆栈在此循环中并禁用 "Stop" 按钮直到它完成。

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

使用定时器后:

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。有关详细信息,请参阅 How to use Swing Timers

基本上,您可以将 Timer 设置为每秒勾选一次(或您需要的任何时间间隔)并安全地更新 state/variables 和 UI,而不会阻塞 UI 或违反 Swing 的线程规则,您只需调用 Timerstop 方法

即可停止 "stop" 按钮中的 Timer

你也应该看看Concurrency in Swing