Search code examples
javaswingtimerjdialogwindowlistener

javax.swing.Timer inside JDialog does not stop when closing JDialog


I have a small application with a main JFrame opening a JDialog as modal. Inside this JDialog I start a javax.swing.Timer that is supposed to stop if the JDialog closes.

public Tasks() {
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 800, 600);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    showTasks();

    t = new Timer(10000, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Tasks.this.showTasks();
        }
    });
    t.start();

}

But it just keeps running.

I tried to implement WindowListener for the JDialog and I overwrote windowClosed, windowClosing and even windowDeactivated ... to no avail

@Override
public void windowClosing(WindowEvent e) {
    // TODO Auto-generated method stub
    System.out.println("Closing");
    t.stop();
}

How can I stop the Timer on close of the JDialog?


Solution

  • I added a WindowListener to this example, and it seemed to work.

    this.addWindowListener(new WindowAdapter() {
    
        @Override
        public void windowClosing(WindowEvent e) {
            System.out.println(e);
        }
    });