stopping a jTimer on frame close

大憨熊 提交于 2019-12-11 12:37:20

问题


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.

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

Thanks


回答1:


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

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.



来源:https://stackoverflow.com/questions/6488048/stopping-a-jtimer-on-frame-close

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!