我有执行以下操作的方法
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer();
Object source = e.getSource();
String stringfromDate = tffromDate.getText();
String stringtoDate = tftoDate.getText();
if (source == button) {
// auto refresh begins
int delay = 0; // 0 seconds startup delay
int period = 7000; // x seconds between refreshes
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
// i still have to truly understand what overide does however
// netbeans prompted me to put this
public void run() {
try {
getdata(stringfromDate, stringtoDate);// run get data
// method
} catch (IOException | BadLocationException ex) {
Logger.getLogger(JavaApplication63.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}, delay, period);
}
if (source == button1) {
timer.cancel();
textarea.setText("");
}
}
我的 GUI 上有 2 个按钮,一个称为获取信息(按钮),另一个称为清除信息(按钮 1)。 我似乎无法获得清晰的信息(按钮1)来停止计时器并清除文本区域,以便可以执行新的搜索。我似乎无法让这停止帮助赞赏。
最佳答案
考虑对您的代码进行这些更改。主要是代码以不同的方式执行这些操作:
将计时器的声明拉到类中,以便稍后可以取消之前启动的同一计时器。
仅在按下开始按钮时创建一个新计时器。
//Pulled up for access to make canceable . protected Timer timer; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); String stringfromDate = tffromDate.getText(); String stringtoDate = tftoDate.getText(); if (source == button) { //Stop existing one before creating new. if(timer != null) { timer.cancel(); } //Now make new timer = new Timer(); // auto refresh begins int delay = 0; // 0 seconds startup delay int period = 7000; // x seconds between refreshes timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { getdata(stringfromDate, stringtoDate);// run get data // method } catch (IOException | BadLocationException ex) { Logger.getLogger(JavaApplication63.class.getName()).log(Level.SEVERE, null, ex); } } }, delay, period); } if (source == button1) { //NULLCHECK if(timer != null) { timer.cancel(); } textarea.setText(""); } }
关于java - 如何停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34232829/