[英]Swing stop timer when exiting jframe
I have a certain task which I run at scheduled intervals. 我有一个特定的任务,我按计划的时间间隔运行。 Basically I show a camera feed on a Label in a JFrame.
基本上我在JFrame中的Label上显示相机。 However when I exit the JFrame the application seems to run.
但是,当我退出JFrame时,应用程序似乎运行。 How can I stop it?
我怎么能阻止它? I have stripped out the details of the code, just leaving the relevent parts in
我已经删除了代码的细节,只是将相关部分留在了
public class TaskCLass extends JFrame {
JPanel p;
JLabel l;
Timer timer;
public TaskCLass() {
p = new JPanel();
l = new JLabel("Window");
add(p);
p.add(l);
setSize(700, 600);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println(e);
timer.purge();
timer.cancel();
System.exit(1);
}
public void windowClosed(WindowEvent e) {
System.out.println(e);
timer.purge();
timer.cancel();
System.exit(1);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
startTask();
}
public static void main(String[] args) {
new TaskCLass();
}
public void startTask() {
TimerTask t = new TimerTask() {
@Override
public void run() {
//.........
}
};
timer = new Timer();
timer.schedule(t, 0, 200);
}
}
Better to use a Swing Timer if the scheduled code is modifying the GUI. 如果计划的代码正在修改GUI,最好使用Swing Timer 。 Otherwise if you are using the non-Swing Timer than you need to shut it down with cancel() .
否则,如果您使用非Swing Timer ,则需要使用cancel()将其关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.