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

1.1k views Asked by At

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.

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.

What confuses me in this case is the invocation of the AWT event dispatcher thread (EDT) for creation of the Swing components. I would just have added all GUI elements inside the SWT UI thread. I am not sure why it's preferable to split the GUI creation between both threads.

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?

1

There are 1 answers

5
unique_ptr On

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. This method checks whether the current thread is a UI thread or not and throws an error. 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