Java – the swing button does not react immediately! How can I change?
I built a form with the visual editor of NetBeans When I press one of the buttons, it should do the following:
>Set it to off > perform tasks that take some time > the button is enabled again when the task is complete
However, the following happens:
>The button remains pressed until the task is completed > when the task is completed, the buttons will be enabled / disabled very quickly (they will happen, but you won't notice them)
This behavior is not what I want I tried to use redraw on JButton, on JFrame, even on JPanel with buttons, but I couldn't seem to make it do what I wanted Some tips?
Solution
When you work in a button callback, you will stop the GUI drawing thread until it is complete
What you need to do is generate a thread to perform long-running tasks, and then let the thread use swing utilities Invoker () updates the UI on completion Not using invoker is not thread safe and is usually a bad mojo
A basic example is:
button.setEnabled(false);
new Thread(new Runnable() {
public void run() {
// Do heavy lifting here
SwingUtilies.invokelater(new Runnable() {
public void run() {
button.setEnabled(true);
}
});
}
}).start();
