简体   繁体   English

Java计时器延迟无法正常工作

[英]Java timer delay not working properly

I'm trying to use timer delay from the javax.swing.Timer class. 我正在尝试使用javax.swing.Timer类中的计时器延迟。
I'm trying to have a label (a temperature) in a JFrame updated every 5 seconds, however the label sometimes gets updated in 1 second. 我试图在JFrame中每5秒更新一次标签(温度),但是有时标签会在1秒内更新。 I want it to happen only in 5 seconds. 我希望它仅在5秒钟内发生。
Here is a portion of my code: 这是我的代码的一部分:

int delay = 5000;           //milliseconds    
ActionListener taskPerformer = new ActionListener() {
                  public void actionPerformed(ActionEvent evt) {
                        tempLabel.setVisible(true);
                        String currTemp = null; //current temperature
                        try {
                            currTemp = getWeatherData.getTemp(locationIndex);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        tempLabel.setText("Temperature :  " + currTemp);
                  }
              };
              Timer timer= new Timer(delay, taskPerformer);
              timer.setRepeats(true);
              timer.start();  

What's happening? 发生了什么? Thanks for reading 谢谢阅读

Haven't used Timer object from swing. 尚未从摆动中使用Timer对象。 But from what i can read, the "delay" you are using, is actually speed? 但是从我的理解中,您正在使用的“延迟”实际上是速度吗?

https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

Look into timer.setInitialDelay(pause); 查看timer.setInitialDelay(pause); instead 代替

//EDIT: //编辑:

Might have to give it a delay in between every 'successful run' instead of just: 可能必须在每次“成功运行”之间延迟一下时间,而不仅仅是:

Timer timer= new Timer(delay, taskPerformer); 
timer.setDelay(delay); 
timer.setRepeats(true); 
timer.start(); 

The amount of time can be affected by a number of things. 时间的长短会受到许多因素的影响。 It's important to remember, a Timer is not accurate, it's only suppose to guarantee a minimum amount of time between ticks. 重要的是要记住, Timer是不准确的,只是要保证滴答之间的时间最少。

However, because Timer tick within the context of the EDT and I have no idea what getWeatherData.getTemp is actually doing, it's possible that it's blocking the EDT and preventing the UI from been updated ... or a whole bunch of other things in your code which you're not showing us. 但是,由于Timer在EDT的上下文中滴答getWeatherData.getTemp而我不知道getWeatherData.getTemp实际在做什么,因此有可能阻止了EDT并阻止了UI的更新……或者您的其他一堆东西您没有显示给我们的代码。

It might be better to use a SwingWorker 使用SwingWorker可能更好

public class TempatureWorker extends SwingWorker<Void, String> {

    private int locationIndex;

    public TempatureWorker(int locationIndex) {
        this.locationIndex = locationIndex;
    }

    @Override
    protected Void doInBackground() throws Exception {
        while (!isCancelled()) {
            publish(getWeatherData.getTemp(locationIndex));
            Thread.sleep(5000);
        }
        return null;
    }

    @Override
    protected void process(List<String> values) {
        String last = values.get(values.size() - 1);
    }

}

You have to work out how you want to update the UI from here, so long as you're doing from process method. 只要您从process方法中进行操作,就必须弄清楚如何从此处更新UI。 You could pass a reference of the JLabel to the worker, but I'd be tempted to use an observer pattern instead, as it decouples the worker. 您可以将JLabel的引用传递给工作人员,但是我很想使用观察者模式,因为它使工作人员分离。

See Worker Threads and SwingWorker for more details 有关更多详细信息,请参见工作线程和SwingWorker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM