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

后端 未结 3 982
离开以前
离开以前 2020-12-09 20:01

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 automat

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 20:54

    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

提交回复
热议问题