Search code examples
javajoptionpane

How to make my JOptionPane dialogue box disappear after 10 seconds


I have a method in Java to catch exception and show in a dialogue box . I would like to make the dialogue box only for 10 seconds and should disappear after that . My code is below

private void errorpopup(Exception m)
{
      JOptionPane.showMessageDialog(
              null,
              new JLabel("<html><body><p style='width: 300px;'>"+m.toString()+"</p></body></html>", JOptionPane.ERROR_MESSAGE));

}

Please provide your valuable suggestions and thanks in advance.


Solution

  • SwingUtilities.getWindowAncestor(component) is a method that returns the first ancestor window of the component.

    You can use this in conjunction with your JLabel (as the component) to get a reference to the JOptionPane Message Dialog Window which you could then close within a timer method set to 10 seconds; something like so:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    
    public class TestClass {
    
        public static void main(String[] args)
        {
            errorpopup(new Exception("Error"));
        }
    
        private static void errorpopup(Exception m)
        {
            JLabel messageLabel = new JLabel("<html><body><p style='width: 300px;'>"+m.toString()+"</p></body></html>");
            Timer timer = new Timer(10000, 
                new ActionListener()
                {   
                    @Override
                    public void actionPerformed(ActionEvent event)
                    {
                        SwingUtilities.getWindowAncestor(messageLabel).dispose();
                    }
                });
            timer.setRepeats(false);
            timer.start();
            JOptionPane.showMessageDialog(null, messageLabel, "Error Window Title", JOptionPane.ERROR_MESSAGE);
        }
    }
    

    Alternatively, this link has another example of how it could be done: How to close message dialog programmatically?

    You would need to do a little bit of work to make it fit your purpose but it shows how you could display the countdown to the user which is neat.