How can Swing dialogs even work?

前端 未结 2 995
Happy的楠姐
Happy的楠姐 2021-02-07 05:29

If you open a dialog in Swing, for example a JFileChooser, it goes somewhat like this pseudocode:

swing event thread {
  create dialog
  add listener to dialog close e         


        
2条回答
  •  被撕碎了的回忆
    2021-02-07 05:32

    The existing event dispatch thread is blocked, and so swing creates another thread that pumps the events. This is then the event dispatch thread for the duration of the dialog.

    Swing creates a separate native thread for pumping native OS window messages. This is separate from the AWT event thread.

    On Windows, you see these threads

      "AWT-Windows"   - the native UI thread
      "AWT-EventQueue-0" - the current AWT event dispatch thread
    

    EDIT: The downvote is correct. This is not true, at least not in all cases.

    Modal dialogs often take care of pumping AWT events themselves. If you run the code

    SwingUtilities.invokeAndWait(new Runnable()
    {
        public void run()
        {
            JOptionPane.showInputDialog("hello");
        }
    });
    

    and then break, looking at the threads, you will see only one EventQueue thread. The show() method of JOptionPane pumps events itself.

    Frameworks like Spin and Foxtrot take the same approach - they allow you to create a long running blocking method on the EDT, but keep the events flowing by pumping events themselves. It is possible for swing to have multiple dispatch threads (I'm sure this was the case with older versions of swing) but now that multicore is common, the concurrency issues, in particular ensuring changes on one thread are correctly published to other threads, mean that using multiple EDTs produces bugs in the current implementation. See Multiple Swing event-dispatch threads

提交回复
热议问题