What is "event-dispatch-thread"

To Event Dispatch Thread (EDT) is the thread that is used by AWT and Swing to render the screen and also to capture and process keyboard and mouse events and operating system messages relevant to the GUI.

Because it is a thread that needs to run continuously, it is not recommended to use it to perform computationally intensive or slow tasks such as network data recovery, file manipulation, and more. The reason for this is that when this thread is occupied for a long time, the events sent by the operating system accumulate and the screen stops being redesigned, causing the GUI to become non-responsive, frozen and locked, being then unlocked only when all the tasks she is performing are completed.

How Java Graphical Interface Environments Are Not thread-safe, this is the only thread that can safely handle the GUI components (instantiating, updating, setting values to text fields, etc.). Trying to manipulate components or actions of these components outside this Thread may cause problems of timing of events.

To start an EDT, there are two ways:

  • From Java 1.1 or higher:
EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        // Aqui se manipula a interface Swing.
    }
});
  • From Java 8 (more succinct than the previous form):
EventQueue.invokeLater(() -> {
    // Aqui se manipula a interface Swing.
});