How do I know if I'm on the event dispatch thread?

后端 未结 2 1426
猫巷女王i
猫巷女王i 2021-01-04 02:36

1.Consider my code is on some line of a JPanel that I have, am I automatically on EDT?

2.Same question for all other classes which are not belong to GUI, JPanels o

相关标签:
2条回答
  • 2021-01-04 03:07

    As per my comment: When all else fails, the SwingUtilities class has a static method that you can use: SwingUtilities.isEventDispatchThread()

    With regards to number 3) definitely use a background thread.

    And as far as I know, there is no "general rule". Yes code in your GUI should be on the EDT, but if you have a bug somewhere, it may not be, though usually it is. Same for Swing listeners.

    0 讨论(0)
  • 2021-01-04 03:12
    1. No.
    2. No.
    3. Background thread.

    If code running outside the EDT calls a method defined in a GUI class, that code will not be run on the EDT but in the calling thread.

    If code running in the EDT calls code defined in a non-GUI class, that code will run on the EDT.

    The rule is that if you're not creating a different thread, the method you're calling will run on the thread the calling code is running from – threads do not correspond to what classes methods are defined in.

    Methods that will run on the EDT are event listeners, when they're called by Swing – not by you. (They still might be if you're calling them from the EDT though.)

    Also, any code inside the Runnable.run() method passed to SwingUtilities.invokeLater() and invokeAndWait() is also run on the EDT.

    Any normal methods you call from the EDT will run on the EDT.

    Any code called from a Thread you create (whether using threads directly, or ExecutorService, or SwingWorker.doInBackground()) is not on the EDT. Your program's main() method is also not on the EDT.

    0 讨论(0)
提交回复
热议问题