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()
, usepublish(V... chunks)
to send data toprocess(List<V> chunks)
. You need to overrideprocess(List<V> chunks)
. Also note thatprocess(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 fromdoInBackground()
by usingget()
. -
Note that
SwingWorker<T,V>
is generic, and you need to specify the types.T
is the type of object returned fromdoInBackground()
andget()
, whileV
is the type of elements you passed toprocess(List<V> chunks)
viapublish(V... chunks)
. -
execute()
method starts the swing worker by invokingdoInBackground()
first.
For more on this, please read Concurrency in Swing.