如何在ActionListener中继续更新JLabel?

时间:2016-01-21 23:01:48

标签: java swing actionlistener jlabel

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

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

1 个答案:

答案 0 :(得分:1)

简短回答,使用Swing Timer。有关详细信息,请参阅How to use Swing Timers

基本上,您可以将Timer设置为每秒钟(或您需要的任何时间间隔)并安全地更新状态/变量和UI,而不会阻止UI或违反Swing的线程规则,您可以停止您的&#34;停止&#34;中的Timer只需拨打stop&#39; $scope.countsChart.options = { deepWatchData: false, chart: { type: 'multiBarChart', margin: { top: 20, right: 20, bottom: 45, left: 45 }, clipEdge: true, duration: 500, stacked: true, showControls: false, xAxis: { showMaxMin: false, tickFormat: d => $scope.countsChart.selectedGranularity().tickFormat(d) }, yAxis: { axisLabelDistance: -20, tickFormat: d => parseInt(d).toLocaleString() }, useInteractiveGuideline: false, interactive: true, tooltips: true, tooltipContent: (key, x, y, e, graph) => '<h1>Test</h1>' } }; 方法

即可

您还应该看看Concurrency in Swing