2

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.

Gergely Toth
  • 6,638
  • 2
  • 38
  • 40
Ganesh V
  • 23
  • 6

1 Answers1

2

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.

Community
  • 1
  • 1
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/13344556) – Hunter Turner Aug 15 '16 at 16:24
  • @HunterTurner In this case flagging as a duplicate would be the correct course of action, not copying the answer. – user1803551 Aug 15 '16 at 16:45
  • How do I do that? EDIT: I'm assuming I'm lacking privileges to do that. –  Aug 15 '16 at 16:48
  • There should be a "flag" option under the question. – user1803551 Aug 15 '16 at 16:52
  • There's not. I only have 7 rep so I assume that option will appear in future. –  Aug 15 '16 at 16:54
  • 1
    Use a Swing timer instead. See the link I gave to the OP. – user1803551 Aug 18 '16 at 16:32