Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid freeze after action on JButton

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

like image 624
Vincent Roye Avatar asked Dec 10 '25 19:12

Vincent Roye


1 Answers

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.

like image 59
Tudor Avatar answered Dec 13 '25 07:12

Tudor