Reputation: 123
I am having a problem with a JButton
named saveChanges
remaining focused for too long when pressed, and I am not sure why this is happening. Below is an excerpt from my code:
saveChanges.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveChanges.setFocusPainted(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// execute some code which inserts records into a database
setCursor(Cursor.getDefaultCursor());
}
}
The code in this method takes about 5-10 seconds to execute but for some reason the cursor returns to the default cursor state several seconds before the saveChanges
button returns to its non-focused state and I can't figure out why. Any help would be greatly appreciated!
Upvotes: 2
Views: 71
Reputation: 1429
Non-GUI processes should be executed on a separate thread from the Event Dispatch Thread (EDT). Use a SwingWorker to handle these operations.
Upvotes: 0
Reputation: 347194
Swing is a single threaded environment, anything that blocks the Event Dispatching Thread, used by Swing to process new events, including repaint requests, will cause the UI to look like it's frozen, because it is.
Have a look at Concurrency in Swing for more details.
Equally, Swing is not thread safe, this means that any updates made to the UI must be made from within the context of the EDT.
You could use a SwingWorker
to do the long running process in the background (from within it's doInBackground
method) and update the state of the UI by overriding it's done
method, which is called from within the context of the EDT once the doInBackground
method has exited.
Take a look at Worker Threads and SwingWorker for more details
Upvotes: 3