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

爱⌒轻易说出口 提交于 2019-11-27 02:47:58

问题


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?


回答1:


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");
    }
}



回答2:


Yes - of course you can. Have you tried to schedule a close?

JFrame f = new JFrame();
final JDialog dialog = new JDialog(f, "Test", true);

//Must schedule the close before the dialog becomes visible
ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();     
s.schedule(new Runnable() {
    public void run() {
        dialog.setVisible(false); //should be invoked on the EDT
        dialog.dispose();
    }
}, 20, TimeUnit.SECONDS);

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

 System.out.println("Dialog closed");

The above program will close the dialog after 20 seconds and you'll see the text "Dialog closed" printed to the console




回答3:


I would use a Swing Timer. When the Timer fires the code will be executed in the Event Dispatch Thread automatically and all updates to the GUI should be done in the EDT.

Read the section from the Swing tutorial on How to Use Timers.



来源:https://stackoverflow.com/questions/1306868/can-i-set-a-timer-on-a-java-swing-jdialog-box-to-close-after-a-number-of-millise

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