[英]perfomance between timer vs for loop in java swing?
我嘗試測試在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的最佳解決方案。 謝謝。
您應該使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.