Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Delay MessageDialogBox in Java?

Tags:

java

swing

So in this chunk of code:

//Actions performed when an event occurs.
    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        //If btnConvertDocuments is clicked, the FileConverter method is called and the button is then disabled [so as to prevent duplicates].
        if (command.equals("w"))
        {
            new Thread(new Runnable() 
            {
                public void run() 
                {
                    FileConverter fc = new FileConverter();

                }
             }).start();
            btnConvertDocuments.setEnabled(false);
            //Validation message ensuring completion of the step.
            JOptionPane.showMessageDialog(this, "Step 1 Complete!", "Validation", JOptionPane.INFORMATION_MESSAGE);
        }

It seems like the message dialog window pop-ups way too fast, before the FileConverter method isn't even finished being called. I was wondering if the placement of JOptionPane was correct, or if there was a way to delay a message until the method finished processing?

like image 852
This 0ne Pr0grammer Avatar asked Aug 17 '26 23:08

This 0ne Pr0grammer


2 Answers

You can use the SwingWorker.

Have a look here, java tutorial.

SwingWorker worker = new SwingWorker<Void, Void>() {
    @Override
    public Void doInBackground() {
        FileConverter fc = new FileConverter();
        return null;
    }

    @Override
    public void done() {
        JOptionPane.showMessageDialog(this, "Step 1 Complete!", "Validation", JOptionPane.INFORMATION_MESSAGE);
    }
};
like image 194
oliholz Avatar answered Aug 20 '26 14:08

oliholz


You should use a Swing Timer with a delay, instead of using your own Thread and Runnable for this.

You can use Swing timers in two ways:

  • To perform a task once, after a delay. For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
  • To perform a task repeatedly. For example, you might perform animation or update a component that displays progress toward a goal.

An example from the documentation:

  int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          //...Perform a task...
      }
  };
  Timer myTimer = new Timer(delay, taskPerformer);
  myTimer.setRepeats(false);
  myTimer.start();
like image 24
Jonas Avatar answered Aug 20 '26 12:08

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!