9.19. Using Swing and AWT Inside SWT

Problem

You want to use Swing or AWT graphical elements inside an SWT application.

Solution

SWT (in Eclipse 3.0) supports embedding Swing/AWT widgets inside SWT widgets. Before Version 3.0, such support worked only on Windows. In Eclipse 3.0, it’s now working in Windows for JDK 1.4 and later, as well as in GTK and Motif with early-access JDK 1.5.

Discussion

To work with AWT and Swing elements in SWT, you use the SWT_AWT class. As an example (SwingAWTApp at this book’s site), we’ll create an application with an AWT frame and panel, as well as a Swing button and text control. We’ll start with a new SWT composite widget:

Composite composite = new Composite(shell, SWT.EMBEDDED);
composite.setBounds(20, 20, 300, 200);
composite.setLayout(new RowLayout( ));

Now add an AWT Frame window object to the composite using the SWT_AWT.new_Frame method, and add an AWT Panel object to the frame:

java.awt.Frame frame = SWT_AWT.new_Frame(composite);
java.awt.Panel panel = new java.awt.Panel( );
frame.add(panel);

We can now work with Swing controls. In this example, we’ll add a Swing button and a Swing text control to the AWT panel:

final javax.swing.JButton button = new javax.swing.JButton("Click Me");
final javax.swing.JTextField text = new javax.swing.JTextField(20);
panel.add(button);
panel.add(text);

All that’s left is to connect the button to a listener to display a message when that button is clicked. You can see how that works in Example 9-5.

Example 9-5. Using Swing ...

Get Eclipse Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.