Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

SWT, Swing or AWT: Which is right for you?

By providing a comparison of Eclipse's SWT with the Java Swing and Abstract Windows Toolkit (AWT)
GUI tool kits, this article helps developers of new applications decide which to choose. Read
descriptions of each tool kit's basic features, and the pros and cons of using each.

Introduction

Other developerWorks authors have shown how to handle the tricky migration between
Swing and SWT . This article is intended to help you decide which GUI tool kit to choose
before starting a project.

But first: Why is there more than one Java™ GUI tool kit? The best answer is that one size
does not fit all, nor is there a one-size-fits-all GUI tool kit to be invented soon. Each tool kit
offers advantages and disadvantages that make selecting one more appropriate, given your
needs and intended audience.

Let's learn about each of these tool kits.

A look at AWT

Abstract Windows Toolkit (AWT) is the original Java GUI tool kit. AWT's main advantages
are that it comes standard with every version of Java technology, including Java
implementations in old Web browsers, and it is very stable. This means you do not need to
install it, you can depend on it being available everywhere you find a Java runtime
environment, and it will have the features you expect.

AWT is a very simple tool kit with limited GUI components, layout managers, and events .
This is because Sun Microsystems decided to use a lowest-common denominator (LCD)
approach for AWT. Only GUI components defined for all Java host environments would be
used. As a result -- and unfortunately -- some commonly used components, such as Tables,
Trees, Progress Bars, and others, are not supported. For applications that need more
component types, you need to create them from scratch. This is a big burden.

In general for AWT (and also Swing and SWT), each event type has an associated
XxxListener interface (and possibly XxxAdapter null implementation), where Xxx is the event
without the Event suffix (for example, KeyListener for a KeyEvent), which is used to pass
the events to handlers. Applications register with the event source (the GUI component or
widget) for the events they are interested in processing. Some listeners handle multiple
events.

One nice feature of AWT is that it, in general, supports automatic disposal of GUI
components. This means that you rarely need to dispose components. The exception is high-
level components, such as Dialogs and Frames. If you create resources that consume
significant host resources, you can dispose of them manually.
AWT components are thread-safe, which means you do not need to be concerned as to which
thread in your application updates the GUI. This can eliminate many GUI update problems,
but can make AWT GUIs run slower.

AWT allows you to build GUIs top-down or bottom-up or in any combination. By top-down,
I mean creating a container component before any of its children. By bottom-up, I mean
creating children before creating their containing (or parent) component. Thus, a component
can exist without a parent container, and its parent can change over time.

AWT GUIs, in general, are not accessible. There is no API for an AWT programmer to
specify accessibility information. Accessibility deals with how well an application can be
used by people with disabilities. To be accessible an application, together with the platform it
runs on, must enable PwDs to use the application with the appropriate assistive technologies
(tools that provide alternate user interfaces). Many governments and corporations have
standards that require applications to be enabled for accessibility.

Sun wanted the Java language to be a "write once, run everywhere" (WORE) environment.
This means Java code could be developed and tested on one host (Windows®, for example)
and be expected to run the same on any other Java host without testing. For the most part,
Java technology succeeded, but AWT was a weak spot. Because AWT depended on host GUI
peer controls (where each AWT component has a parallel host control or peer) to implement
the GUI, the GUI looked and -- more importantly -- behaved differently on different hosts.
This resulted in a "write once, test everywhere" (WOTE) situation, which was less than
satisfactory.

AWT provides a rich graphics environment, especially in Java V1.2 and beyond. Through the
Graphics2D object, and Java2D and Java3D services, many powerful graphical applications,
such as drawing and charting packages and, combined with JavaSound, competitive
interactive games, can be created.

A look at Swing

Java Swing, also known as a part of the Java Foundation Classes (JFC), was an attempt to
solve most of AWT's shortcomings. In Swing, Sun created a very well-engineered, flexible,
powerful GUI tool kit. Unfortunately, this means Swing takes time to learn, and it is
sometimes too complex for common situations.

Swing is built on parts of AWT. All Swing parts are also AWT parts. Swing uses the AWT
event model and support classes, such as Colors, Images, and Graphics. The Swing
components, layout managers, and events are summarized below. As you can see, these sets
are far more extensive than that supplied by AWT and compares well to the SWT set.

To overcome the variation in behavior across different hosts, Swing minimized its
dependence on host controls. In fact, Swing uses peers for only top-level components like
windows and frames. Most components (JComponent and its subclasses) are emulated in
pure-Java code. This means that Swing is naturally portable across all hosts. Thus, Swing
does not typically look like a native application. In fact, it has multiple looks, some that can
emulate -- although often not exactly -- different hosts and some that provide unique looks.
Swing uses the term heavyweight for peer-based components and lightweight for emulated
components. In fact, Swing supports mixed heavy and light components in a single GUI, such
as mixing AWT and Swing controls in the same JContainer, but care must be taken with
drawing order if the components overlay each other.

Swing may not be able to take advantage of hardware GUI accelerators and special host GUI
operations. As a result, Swing applications may be slower than native GUIs. Sun has worked
hard on the performance of the recent versions of Swing (Java V1.4 and 1.5), and this
disadvantage is becoming less noticeable. Because Swing's design is more robust, its code
base is larger. This can mean it takes a beefier machine to run it than AWT or SWT might.

Beyond more components, layout mangers, and events, Swing has many features that make it
more powerful than AWT. Some of the more important ones are:

Separation of model from the view and controller


For all components with models (such as buttons, lists, tables, trees, rich text), the
model is separate from the component. This allows the model to be adapted to the
needs of the application and for it to be shared by multiple views. Default models per
component type are provided for convenience.
Programmable look and feel
Each component's look (appearance) and feel (how it reacts to input events) is
controlled by a separate and dynamically replaceable implementation. This allows the
look and feel of all or part of a Swing-based GUI to change.
Renderers and editors
Most components that show model content, such as lists, tables, and trees, can process
model elements of almost any type. This is done by mapping a renderer or editor for
each component type and model type. For example, a table with a column containing
java.util.Date values can have special code to present the date value and edit the
date value. Each column can have different types.
Accessibility
Creating a GUI that is accessible to people with disabilities is important. Swing offers
an extensive infrastructure and API for enabling GUIs for accessibility. This support
is independent of but integrates with the host accessibility support, if any.

Like AWT, Swing supports automatic disposal of GUI components. Swing also supports the
AWT bottom-up and top-down construction methods.

Unlike AWT, Swing components are not thread-safe, which means you need to be concerned
as to which thread in your application updates the GUI. If you err in thread use, unpredictable
behavior, including user interface glitches, can occur. Utility routines exist to help manage
threading issues.

Like AWT, one of Swing's advantages is that it comes standard with Java technology. This
means you do not need to install it. Unfortunately, Swing has evolved a lot, so it is easy to
become dependent on features provided in more recent versions of the Java language, which
may force users to upgrade their Java runtimes.

A look at SWT
SWT is a low-level GUI tool kit comparable in concept to AWT. JFace is a set of enhanced
components and utility services to make building GUIs with SWT easier. The builders of
SWT learned from the AWT and Swing implementations and tried to build a system that had
the advantages of both without their disadvantages. In many ways, they succeeded.

SWT is a lot like AWT in that it is based on a peer implementation. It overcomes the LCD
problem faced by AWT by defining a set of controls adequate to make most office
applications or developer tools and then, on a host-by-host basis, creating emulated (like
Swing) controls for any not supplied by the particular host. For most modern hosts, nearly all
the controls are based on native peers. This means that an SWT-based GUI has a host look
and feel, and host performance. This avoids the most widely held complaints with AWT and
Swing. Certain hosts have low-function controls, so SWT supplies extended, often emulated,
versions (often with "C" as the first letter in their names) to allow the more generally
expected behavior.

SWT is different from AWT in how the peers work. In SWT, the peers are just wrappers on
host controls. In AWT, peers can provide services to minimize the differences between hosts
(this is where AWT ran into a lot of its behavior issues). This means that an SWT application
is really a host application, with all the good and bad points that entails. It also means that
SWT does not fully achieve the WORE goal; it is more a WOTE solution. That said, SWT
does a remarkable job of creating a portable solution, albeit not as well as Swing.

The SWT widgets, layouts, and events are summarized below . As you can see, these sets are
far more extensive than that supplied by AWT and compares well to the Swing set.

A look at SWT

SWT is a low-level GUI tool kit comparable in concept to AWT. JFace is a set of enhanced
components and utility services to make building GUIs with SWT easier. The builders of
SWT learned from the AWT and Swing implementations and tried to build a system that had
the advantages of both without their disadvantages. In many ways, they succeeded.

SWT is a lot like AWT in that it is based on a peer implementation. It overcomes the LCD
problem faced by AWT by defining a set of controls adequate to make most office
applications or developer tools and then, on a host-by-host basis, creating emulated (like
Swing) controls for any not supplied by the particular host. For most modern hosts, nearly all
the controls are based on native peers. This means that an SWT-based GUI has a host look
and feel, and host performance. This avoids the most widely held complaints with AWT and
Swing. Certain hosts have low-function controls, so SWT supplies extended, often emulated,
versions (often with "C" as the first letter in their names) to allow the more generally
expected behavior.

SWT is different from AWT in how the peers work. In SWT, the peers are just wrappers on
host controls. In AWT, peers can provide services to minimize the differences between hosts
(this is where AWT ran into a lot of its behavior issues). This means that an SWT application
is really a host application, with all the good and bad points that entails. It also means that
SWT does not fully achieve the WORE goal; it is more a WOTE solution. That said, SWT
does a remarkable job of creating a portable solution, albeit not as well as Swing.
Like AWT and Swing layout managers, SWT provides a comprehensive set of layouts. Both
layout systems, combined with nested containers, can generate almost any needed layout
algorithm. All three GUI libraries also support absolute control positioning. The lack of a
SWT BorderLayout equivalent is disappointing. The FormLayout is very nice for creating
form-base input. I think the SWT layout scheme is a little harder to learn to use than the
AWT/Swing set.

Like the AWT and Swing event systems, SWT provides a comprehensive set of events.
Although the events are not one-to-one with AWT/Swing (for example, AWT and Swing
buttons both fire ActionEvent while SWT buttons fire SelectionEvent), they are generally
equivalent.

Many Swing components, such as JTable, have models. SWT control equivalents (such as
Table) do not; they have items, instead. Items are generally limited to showing text or
generally small images (such as icons). To provide a Swing-like model structure, JFace
ContentProviders are used. These providers act as a bridge between the application-supplied
model (such as a java.util.Array for a List or Table), and the control acting as the view. In
order to format arbitrary model objects into items, SWT uses JFace LabelProviders, which
generate a text or iconic form for any model object. This can limit the sophistication of the
display of complex model objects. Other providers, such as ColorProviders and
LabelDecorators, can enhance the display of items. For the special case of Tables, SWT
provide a CellEditor that temporarily links an arbitrary SWT control to a Table cell to act as
an editor for that cell.

SWT does not support automatic disposal of GUI controls. This means that you must
explicitly dispose of any controls or resources, such as colors or fonts, you create, as opposed
to getting from an API call. This effort is eased somewhat as container controls dispose of
their child controls automatically.

SWT only allows you to build GUIs top-down. Thus, a control cannot exist without a parent
container, and its parent cannot, in general, change over time. This approach is much less
flexible than AWT/Swing. Controls are added to a parent container during creation and
removed when disposed. Also, the SWT use of style bits only at construction time can limit
the flexibility of some GUI controls. Many styles are hints only and do not work the same on
all platforms.

Like Swing, SWT components are not thread-safe, which means you need to be concerned
about which thread in your application updates the GUI. If you err in thread use an exception
is thrown. I think this is better than the non-deterministic Swing approach. Special utility
routines exist to help manage threading issues.
SWT GUIs are generally accessible if the supporting host provides accessibility services.
SWT provides a basic out-of-process API for programmers to specify accessibility
information when the default information is inadequate.

SWT provides a limited graphics environment. To date, it does not compare well to the
support of Java2D and Java3D. Eclipse provides a separate feature called Graphical Editing
Framework (GEF) with a component called Draw2D that can be used to create some drawing
applications, such as UML modeling tools. Unfortunately, GEF is difficult to use stand-alone
(meaning outside the entire Eclipse environment).

Unlike AWT and Swing, SWT and JFace do not come with Java technology. They must be
installed separately, as part of an Eclipse installation or as separate libraries. The Eclipse
team has made it fairly easy to install and run SWT independently of Eclipse. The needed
Java archives (JAR) and Dynamic Link Libraries (DLL), and similar libraries for UNIX®
and Macintosh can be downloaded separately from the Eclipse Web site. The JFace libraries
require you to download all of Eclipse and copy out the needed JARs. Once downloaded, the
JARs need to be on the Java CLASSPATH and the DLLs on the system PATH.

Table 1. SWT vs. AWT and Swing Feature comparison


Function/Role/Aspec
AWT Swing SWT (style)
t
Display static text Label JLabel Label, CLabel
Multiple JLabels
Display multi-line Multiple Labels or Label
Multiple Labels or JLabel with
static text with newlines
HTML content
Display multi-line Multiple Labels with JLabel with Multiple Labels with
formatted static text different fonts HTML content different fonts
Single-line text entry TextField JTextField Text(SWT.SINGLE)
Multi-line text entry TextArea JTextArea Text(SWT.MULTI)
Display an image N/A JLabel Label
Display text and
N/A JLabel CLabel
image
setToolTip on
ToolTip pop-up help N/A component, setToolTip on control
subclass JToolTip
Styled text entry N/A JEditorPane StyledText
Select from list of
List JList List
items
Simple push button
Button JButton Button(SWT.PUSH)
with text
Simple push button
N/A JButton Button(SWT.PUSH)
with text and/or image
Drawing area; Canvas JPanel Canvas
possibly for custom
controls
On/off check box CheckBox JCheckBox Button(SWT.CHECK)
ButtonGroup and
Radio selection CheckBoxGroup Group and Menu
menus
Select from a drop-
Choice JComboBox Combo, CCombo
down list
Enter text or select
N/A JComboBox Combo, CCombo
from a drop-down list
Scrollable area ScrollPane JScrollPane Create Scrollable subclass
Dialog, Frame, JDialog, JFrame,
Top level windows Shell with different styles
Window JWindow
Generic window Window JWindow Shell
Frame window Frame JFrame Shell(SWT.SHELL_TRIM)
Shell(SWT.DIALOG_TRIM
Dialog window Dialog JDialog
)
Menu Menu JMenu Menu
MenuItem MenuItem JMenuItem MenuItem
host dependent mnemonics
Menu shortcuts Generic keystrokes same as AWT
and accelerators
Pop-up menu PopupMenu JPopupMenu Menu(SWT.POPUP)
Menu bars MenuBar JMenuBar Menu(SWT.BAR)
Display an insertion
N/A Caret Caret
caret
JTextPane Browser (via embedded
Web browser N/A
(HTML 3.2) browser)
Embed control in web
Applet JApplet Host control (ex. OLE)
page
Generic container of
Panel JPanel Composite
other controls
Generic container of
Panel (if drawn JPanel with a
other controls with a Composite(SWT.BORDER)
manually) Border
border
Generic container of
JPanel with a
other controls with a N/A Group
TitledBorder
border and title
Radio button (one of
Checkbox JRadioButton Button(SWT.RADIO)
set on)
Control extent of RadioButtonGrou
CheckboxGroup Group
radio buttons p
JButton with
Arrow buttons N/A Button(SWT.ARROW)
image
Supports int'l text via Many components support
same as AWT
orientations ComponentOrientation styles for this
Policy and Manager
Focus Traversal same as AWT Next on control
objects
Custom dialogs Dialog subclass JDialog subclass Dialog subclass
Access to system Display services (less robust
EventQueue services same as AWT
events than AWT)
System access dialogs FileDialog JColorChooser, ColorDialog,
JFileChooser DirectoryDialog, FileDialog,
FontDialog, PrintDialog
Display simple N/A (must subclass JOptionPane static MessageBox with numerous
message dialog Dialog) methods styles
Display simple N/A (must subclass JOptionPane static N/A (classes exist in JFace
prompting dialog Dialog) methods to do this)
BorderLayout,
AWT plus
CardLayout, FillLayout, FormLayout,
BoxLayout,
Layout managers FlowLayout, GridLayout, RowLayout,
CenterLayout,
GridLayout, StackLayout
SpringLayout
GridBagLayout
Basic drawing control Canvas JPanel Canvas
Graphics and
Graphics2D objects -
Basic shapes and text, GC object - Basic shapes
Basic drawing same as AWT
arbitrary Shapes and and text
Strokes, Bezier, fills,
etc.
Drawing transforms Affine, composites same as AWT N/A
BufferedImage,
Off screen drawing same as AWT Image, drawImage
drawImage
Automatic or Manual unless provided by
Double buffering Manual
manual host control
PrintJob and
Printing same as AWT draw to Printer device
PrintGraphics
Custom colors Color same as AWT Color
Custom fonts Font, FontMetrics same as AWT Font
Cursors selection Cursor same as AWT Cursor
load from file, create
load from file, create
Image features dynamically, extensive same as AWT
dynamically, basic edits
edits
Input automation Robot same as AWT N/A
Display a tool bar N/A JToolBar ToolBar, CoolBar
Display a progress barN/A JProgressBar ProgressBar
Divide space between
N/A JSplitPane Sash or SashForm
areas
Display tabbed areas N/A JTabbedPane TabFolder, CTabFolder
Display tabular info N/A JTable Table
Format table columns N/A TableColumn TableColumn
Display hierarchical
N/A JTree Tree
info
Select from range of
N/A JSlider Slider
values
Select from discrete
N/A JSpinner Scale
range of values
Toolkit,
Access to the base
GraphicsConfiguration same as AWT Display
display
, GraphicsDevice
Add items to the
N/A N/A Tray
system tray
Key: N/A - Not available. In many cases, this feature can be created, with varying degrees of
difficulty, by creating custom controls or containers of controls or by other custom
programming.

Conclusion

This article provided a comparison between the Eclipse's Standard Windows Toolkit with
JFace, and the Java's Swing and Abstract Windows Toolkit GUI tool kits. Through the
comparisons provided here, you can decide which GUI tool kit to use for your new
applications.

In most cases, the decision is between Swing and SWT combined with JFace. In general,
each of these tool kits is complete and powerful enough to build full-function GUIs, but
Swing is generally superior to SWT alone (used without JFace). Swing has the advantage of
being built into Java technology, is completely portable, and arguably has a better
architecture. Swing also has the advantage for advanced graphical applications. SWT has the
advantage of being implemented as a native application which increases the performance and
native compatibility of SWT-based GUIs.

If you are developing only for one platform, SWT has an advantage in host compatibility,
including integration with host features, such as use of ActiveX controls under Windows.

You might also like