I have a method that can take a long time to be executed. Let's call it longTime();
This method is called from an action listener on a button.
I want to display a "Please wait.." message while this method is executing.
The problem is that the Jframe doesn't respond, it seems to be stuck or waiting for something.
Important note: The running time of longTime() can be different. The problem appears only when it takes more than 2-3 seconds.
I tried to do all of these in invokeLate but that didn't help.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
JLabel label = new JLabel("Please wait...");
label.setFont(new Font("Serif", Font.PLAIN, 25));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
frame.pack();
frame.setAlwaysOnTop(true);
frame.setVisible(true);
try{
longTime(); //HERE IS THE FUNCTION THAT TAKES A LONG TIME
}catch(Exception e){ }
frame.dispose(); //AFTER THE LONG FUNCTION FINISHES, DISPOSE JFRAME
}
});
Any ideas of how to fix this?
All lengthy tasks should occur in a separate thread, in order to prevent the GUI thread (Event Dispatch Thread) being blocked. I would suggest you look into using a SwingWorker object to execute the lengthy task and perform actions upon completion.
You can read more about this subject at http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html.
there are two ways, by using JLayer (Java7) based on JXLayer (Java6) or Glasspane, use JLabel (with intermediate Icon) invoked
from SwingWorker
(easiest) from Runnable.Thread (output to the Swing GUI must be wrapped in invokeLater)
carefully with Concurency in Swing, all changes must be done on EDT
don't reinvent the wheel, code examples by @camickr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With