Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a timer on a Java Swing JDialog box to close after a number of milliseconds

Hi is it possible to create a Java Swing JDialog box (or an alternative Swing object type), that I can use to alert the user of a certain event and then automatically close the dialog after a delay; without the user having to close the dialog?

like image 611
Dave Avatar asked Aug 20 '09 15:08

Dave


1 Answers

This solution is based on oxbow_lakes', but it uses a javax.swing.Timer, which is intended for this type of thing. It always executes its code on the event dispatch thread. This is important to avoid subtle but nasty bugs

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

public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        final JDialog dialog = new JDialog(f, "Test", true);
        Timer timer = new Timer(2000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });
        timer.setRepeats(false);
        timer.start();

        dialog.setVisible(true); // if modal, application will pause here

        System.out.println("Dialog closed");
    }
}
like image 153
Steve McLeod Avatar answered Oct 06 '22 00:10

Steve McLeod