问题
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