【发布时间】: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