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);
}
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