I’ve built a form with Netbeans’s visual editor. When I press one of the buttons it should do the following :
- set it to disabled
- perform a task that takes some time
- when the task finishes the button will be enabled again
However, the following happens:
- the button remains in a pressed state until the task finishes
- when the task finishes, the enabling/disabling of buttons will be very fast (they will happen, but you won’t notice them)
This behaviour is not something I want. I tried using repaint on the JButton, on the JFrame and even on the JPanel containing the button, but I can’t seem to get it to do what I want. Some hints?
When you do work in a button callback, you are stalling the GUI painting thread until it completes.
What you need to do is spawn a thread to do the long running task, and then have that thread use
SwingUtilities.invokeLater()to update the UI when it completes. Not usinginvokeLateris not thread safe, and is generally bad mojo.A basic example is: