简体   繁体   English

结合SWT和AWT / Swing:采用哪个GUI线程?

[英]Combining SWT and AWT/Swing: which GUI thread to take?

Working on a large scale SWT-based application I just stumbled upon some code using the AWT/Swing bridge which totally confused me and made me think about the implications of using two GUI threads. 在基于SWT的大型应用程序上工作时,我偶然发现了一些使用AWT / Swing桥的代码,这完全使我感到困惑,并使我思考使用两个GUI线程的含义。

public void createContent(final String html) {
    // Bridge to AWT
    frame = SWT_AWT.new_Frame(this);
    rootPane = new JPanel();
    rootPane.setLayout(new GridBagLayout());
    JRootPane rp = new JRootPane();
    rp.getContentPane().add(rootPane);
    rp.validate();
    frame.add(rp);
    frame.validate();

    // Create components in AWT user interface thread (deadlock prevention)
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            initializeLookAndFeel();
            initializeToolbar();
            initializeHTMLEditor();
            setHTML(html, false);
        }
    });

    rootPane.repaint();
    rootPane.validate();
}

Without going into detail, as you might have guessed a lot of Swing elements are added to the "bridge frame" inside the initialization methods. 无需赘述,您可能已经猜到了很多Swing元素都被添加到初始化方法中的“ bridge frame”中。

What confuses me in this case is the invocation of the AWT event dispatcher thread (EDT) for creation of the Swing components. 在这种情况下,令我感到困惑的是为创建Swing组件而调用了AWT事件分配器线程(EDT)。 I would just have added all GUI elements inside the SWT UI thread. 我只会在SWT UI线程中添加所有GUI元素。 I am not sure why it's preferable to split the GUI creation between both threads. 我不确定为什么最好在两个线程之间分配GUI创建。

Probably, someone can elaborate on what happens behind the scenes. 可能有人可以详细说明幕后发生的事情。 Especially on the interaction of both threads using the bridge. 特别是在使用桥的两个线程的交互上。 Why or when would it make sense to dispatch creation of AWT stuff to the EDT like in the code example? 为什么或何时像代码示例中那样将创建AWT内容的工作分配给EDT有意义?

In SWT every UI element has to be created/handled/accessed within a UI thread since there is a checkWidget method call before sending system signals. 在SWT中,必须在UI线程内创建/处理/访问每个UI元素,因为在发送系统信号之前存在一个checkWidget方法调用。 This method checks whether the current thread is a UI thread or not and throws an error. 此方法检查当前线程是否是UI线程,并引发错误。 The reason behind this choice is that the graphical context access is single threaded and this applies for swing too. 这一选择背后的原因是图形上下文的访问是单线程的 ,这适用于挥杆了。 Thus you have to call every widget handling within its proper thread the SWT ones with either Display.syncExec(....) or Display.asyncExec(....) and SWING ones in the EventQueue thread 因此,您必须在其适当的线程中将每个小部件处理调用为Display.syncExec(....)Display.asyncExec(....)的SWT,并在EventQueue线程中调用SWING。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM