【问题标题】:perfomance between timer vs for loop in java swing?java swing中定时器与for循环之间的性能?
【发布时间】:2013-03-27 07:42:54
【问题描述】:

我尝试测试我在 Raspberry PI 上运行的 Swing GUI。我的目标是每 1 秒显示一次系统时间。并且每“cycleTime”秒更新“planValue”。在桌面上测试它是正常的。当我在 RaspPI 上运行时,更新“planValue”或打开弹出新对话框时非常缓慢且有时间延迟。

这是 MainScreen 类

public class MainScreen extends javax.swing.JFrame implements ActionListener {

    private javax.swing.JLabel jLabelPlan;
    private javax.swing.JLabel jLabelSysTime;
    int planValue;
    int cycleTime = 5; //5 seconds
    int counter = 1;

    public MainScreen() {
        initComponents();
        //start timer.
        javax.swing.Timer timer = new javax.swing.Timer(1000,this);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        showDisplay();
    }

    public void showDisplay() {
        DateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
        jLabelSysTime.setText(formatTime.format(Calendar.getInstance().getTime()));
        jLabelPlan.setText(String.valueOf(planValue));
    }
}

如果我创建新的 Timer planTimer

Timer planTimer = new Timer(cycleTime * 1000, new ActionListener() {   
    @Override
    public void actionPerformed( ActionEvent e ) {
        planValue += 1;
    }
});
planTimer.start(); //Timer updPlan start

或在actionPerformed(ActionEvent e)中使用循环

@Override
public void actionPerformed(ActionEvent e) {
    showDisplay();
        if(counter == cycleTime) {
            planValue += 1;
            counter = 1;
        } else {
            counter++;
        }
    }
}

有什么建议吗?或在 Raspberri PI 上运行我的 GUI 的最佳解决方案。谢谢。

【问题讨论】:

  • javax.swing.Timer 足以满足您的需求。另请查看javax.swing.SwingWorker。不要使用循环。而是让计时器每隔1 秒触发一次。
  • showDisplay 可能应该以 repaint(10L); 结尾,因为这就是你想要的。

标签: java swing user-interface timer


【解决方案1】:

您应该使用Timer.setRepeats(true) 让您的计时器重复触发事件。

Timer planTimer = new Timer(cycleTime * 1000, new ActionListener() {   
    @Override
    public void actionPerformed( ActionEvent e ) {
        planValue += 1;
    }
});
plainTimer.setRepeats(true);//Set repeatable.
planTimer.start();

你的timer 变量应该是这样的:

javax.swing.Timer timer = new javax.swing.Timer(1000, new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent evt)
    {
        showDisplay();
    }
});
timer.setRepeats(true);
timer.start();

【讨论】:

  • 当我只使用 1 个 Timer(planTimer) 我的 sysTime 每 5 秒刷新一次时,我应该怎么做 javax.swing.Timer 计时器。
  • 由于两个动作的重复延迟不匹配,所以我建议你为每个动作使用两个计时器。
  • 是的;为了提高效率,两个计时器将“使用单个共享线程执行它们的等待”。
  • @trashgod:是的,你指出了javax.swing.Timer的最主要特征
猜你喜欢
  • 2010-11-13
  • 2015-08-28
  • 2012-01-01
  • 2017-03-01
  • 2011-04-28
  • 2012-11-18
  • 2010-09-20
  • 1970-01-01
相关资源
最近更新 更多