I am quite new to Java so I am sorry for this beginner question.
I have a JButton, when I click on it, there are a few MySQL queries triggered and some updates in the display that take 2 or 3 seconds. During this time my user interface freezes completely. Is there a way to avoid that ? Maybe I should use something like synchronized, thread or runnable but I don't understand very well. Could somebody explain me please ?
Thank you very much.
Regards.
Vincent
Because you are executing the queries on the same thread as the user interface, that thread is unable to receive any user commands in the meantime, thus it "freezes".
The solution is to start a new thread and execute the queries in parallel and then use something like SwingUtilities.invokeLater to update the ui. Something like:
// button action listener code
Thread t = new Thread(new Runnable() {
public void run() {
// execute query here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// update the ui here
}
});
}
});
t.start();
SwingUtilities.invokeLater effectively queues the update action until all pending events on the UI thread have been processed. Read the javadoc here.
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