Andrei Filipchyk
Andrei Filipchyk

Reputation: 182

"Please wait" message with delay

I have a long task and I show "please wait" message during its execution. I use SwingWorker for it. But sometimes long task is not long, so I want to show message with 1 second delay, but I don't know how to do it.

SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>(){
     @Override
    protected String doInBackground() throws InterruptedException 
        /** Execute some operation */   
    }
    @Override
    protected void done() {
        dialog.dispose();
    }
  };

  mySwingWorker.execute();

  JProgressBar progressBar = new JProgressBar();
  progressBar.setIndeterminate(true);
  JPanel panel = new JPanel(new BorderLayout());
  panel.add(progressBar, BorderLayout.CENTER);
  panel.add(new JLabel("Please wait......."), BorderLayout.PAGE_START);
  dialog.add(panel);
  dialog.pack();
  dialog.setLocationRelativeTo(win);
  dialog.setVisible(true);

}

Upvotes: 1

Views: 1145

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347184

Before you start the SwingWorker, start a Swing Timer with (at least) a one second delay and set not to repeat.

Pass this Timer to your SwingWorker so it has access to it. When the worker's done method is called, stop the Timer

If the Timer is triggered, you would display your wait message.

With a little bit of effort, you could wrap the whole thing up in a self contained class, using the SwingWorker's PropertyListener support to detect when the worker was started and completed

Upvotes: 2

Kore
Kore

Reputation: 436

A simple way to do it would be to set

    long startTime = System.getNanoTime();

then before displaying the "please wait" you could check if it was > 1 second (1×10^9 nanos)

this may not be the most efficient way, but it will work

Upvotes: 0

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

Why dont you use Thread.sleep(1000); between each display of "please wait"

Upvotes: 0

Related Questions