我有一个小程序,它将当前日期和当前时间写入文本文件。但是,它会继续写入,直到我关闭帧。所以我添加了一个暂停按钮,希望暂停并恢复程序,而不必关闭并再次启动它(如果这是有道理的。)
无论如何,我能做到这一点吗?
非常感谢提前!!!
请参阅以下代码
class RecordTask extends TimerTask {
public void run() {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("breaths.txt", true)));
out.println(new Date().toString());
out.close();
Breaths++;
lblB.setText("Breaths: " + Breaths);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), e.toString(), "",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void actionPerformed(ActionEvent event) {
// Check if Start button is pressed
if (event.getSource() == startButton) {
int value = (int) txtRate.getValue();
timer = new Timer();
int interval = (int)((((double) 60) / (double) value) * 1000);
timer.scheduleAtFixedRate(new RecordTask(), interval, interval);
startButton.setEnabled(false);
} else // Check if pause button pressed
if (event.getSource() == pauseButton) {
//Pause the breaths
} else // Check if exit button pressed
if (event.getSource() == exitButton) {
// close the program
System.exit(0);
}
}
所以我基本上需要暂停该功能并恢复它。 :)
答案 0 :(得分:0)
而不是java.util.Timer
使用javax.swing.Timer
。它有方法start()
,stop()
。此外,java.util.Timer
对于Swing API并不安全,因为在EDT以外的线程中安排任务并在任务JOptionPane.showMessageDialog
中使用。