JButton ActionListener - GUI updates only after JButton is clicked

Solution 1:

Do not perform any intensive operations within EDT, otherwise the GUI will be unresponsive and you might not see the GUI updates. Best choice you can use is SwingWorker:

  • Override doInBackground(), and put any long operations inside this method so that it will be run on a separate thread rather than the EDT.

  • For any GUI creation or changing states of GUI components within doInBackground(), use publish(V... chunks) to send data to process(List<V> chunks). You need to override process(List<V> chunks). Also note that process(List<V> chunks) is executed on EDT.

  • After doInBackground() returns, done() executes on EDT and you can override it to use it for any GUI updates. You can also retrieve the value returned from doInBackground() by using get().

  • Note that SwingWorker<T,V> is generic, and you need to specify the types. T is the type of object returned from doInBackground() and get(), while V is the type of elements you passed to process(List<V> chunks) via publish(V... chunks).

  • execute() method starts the swing worker by invoking doInBackground() first.

For more on this, please read Concurrency in Swing.