When to use SwingUtilies.invokeAndWait/invokeLater

后端 未结 4 1868
半阙折子戏
半阙折子戏 2021-02-06 01:42

I read somewhere that for any thread that affects the visuals of the gui it should be ran in the EDT using SwingUtilities.invokeAndWait/invokeLater

For a basic gui, is i

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 02:23

    Anything that is called from your

    public static void main(String[] agrs) {
    

    directly (without spawning another thread or using invokeLater) is running on the main thread.

    Accessing GUI objects with the main thread while they may be being accessed (simultaneously) by the EDT (which is triggered by user input) can cause threading issues. Calling invokeLater causes tasks (runnables) to run on the EDT, preventing simultaneous access by other EDT tasks ie. button presses etc.

    If you can be sure the EDT is not busy (before the first window is setVisible(true)) you can access the GUI from the main thread. If you can be sure the EDT has no reference to the component you're working on (it is out of EDT's scope) ie. before it's added to any container, you can access it from main thread without the EDT accessing it simultaneously, as the EDT has no way to reach it.

提交回复
热议问题