在框架关闭时停止jTimer [英] stopping a jTimer on frame close

查看:54
本文介绍了在框架关闭时停止jTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个框架,该框架启动swingTimer来执行定期任务.问题是当我关闭框架时,任务仍然继续.如果希望按下关闭按钮,我希望swingTimer停止.

I have a frame which starts a swingTimer to perform a periodic task. The problem is when I close the frame, the task still continues. I want the swingTimer to stop if the close button is pressed.

我尝试指定EXIT_ON_CLOSEDISPOSE_ON_CLOSE,但是它们不起作用.有人知道我应该怎么做吗?

I have tried specifying EXIT_ON_CLOSE and DISPOSE_ON_CLOSE but these do not work. Does someone know what I should do?

谢谢

推荐答案

Swing Timer具有stop方法.如果框架"(JFrame ??)通过WindowListener结束,则始终可以调用它.

Swing Timer has a stop method. You can always call that if the "frame" (JFrame??) ends via a WindowListener.

另外,根据我的测试,如果EDT停止,计时器应自行停止.例如:

Also, per my tests, the Timer should stop on its own if the EDT stops. For example:

import java.awt.event.*;
import javax.swing.*;

public class StopTimer extends JPanel {
   private static final float FONT_SIZE = 32;
   private Timer myTimer;
   private JLabel timerLabel = new JLabel("000");
   private int count = 0;

   public StopTimer() {
      timerLabel.setFont(timerLabel.getFont().deriveFont(FONT_SIZE));
      add(timerLabel);

      int timerDelay = 1000;
      myTimer = new Timer(timerDelay , new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            count++;
            timerLabel.setText(String.format("%03d", count));
            System.out.println("count: " + count);
         }
      });
      myTimer.start();
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("StopTimer");
      frame.getContentPane().add(new StopTimer());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

如果这对您没有帮助,请执行我已做的事情:发布一个可编译且可运行的小型程序,演示您的问题.

If this doesn't help you, then do what I've done: post a small compilable and runnable program that demonstrates your problem.

这篇关于在框架关闭时停止jTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆