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?
You have to spawn another thread and run your longTime() task in another thread.
Calling invokeLater() still runs it in the UI thread, which you don’t want to block.
Consider following code:
It’s possible that you want to update a data model from that newly spawned thread. That would be the right place to use SwingUtilities.invokeLater(). Don’t update models in this new thread. Models for UI components must be updated in UI thread only. Invoke later does exactly that.