Chapter 7. Standard Widget Toolkit (SWT)

One of the great success stories of the Eclipse Platform has been the overwhelming groundswell of support for its windowing toolkit, SWT. This toolkit offers a fast, thin, mostly native alternative to the most common Java UI toolkits, Swing and Abstract Windowing Toolkit (AWT). Religious debates abound over the relative merits of Swing versus SWT, and we take great pains to avoid these debates here. Suffice it to say that SWT generates massive interest and manages to garner as much, if not more, interest as the Eclipse Platform built on top of it.

The popularity of SWT has forced us to take a slightly different approach with this chapter. The SWT newsgroup was created in July 2003 and since then has generated an average of 136 messages every day. In this book, we could not even scratch the surface of the information available there. Although we could present the illusion of completeness by answering a couple dozen popular technical questions, we would not be doing the topic justice. Instead, we focus on answering a few of the higher-level questions and providing as many forward pointers as we can to further information on SWT available elsewhere. A benefit of SWT’s popularity is the wealth of Web sites, discussion forums, books, and other forms of documentation out there. Thus, although we won’t be able to answer all SWT questions, we hope at least to steer you to the resources that can. However, a handful of questions are asked so often that we can’t resist answering them here.

FAQ 133: What is SWT?

Standard Widget Toolkit (SWT) is the UI toolkit used by the Eclipse Platform and most other Eclipse projects. Its stated goal, according to the SWT home page, is to provide “efficient, portable access to the user-interface features of the operating systems on which it is implemented.” Its goal is not to provide a rich user-interface design framework but rather the thinnest possible user-interface API that can be implemented uniformly on the largest possible set of platforms while still providing sufficient functionality to build rich graphical user interface (GUI) applications.

SWT is implemented by creating thin native wrappers for the underlying operating system’s user-interface APIs. The bulk of SWT’s source is Java code, which defers as much work as possible to the appropriate operating system native. Thus, when you create a tree widget in SWT, it calls through to the operating system to create a native tree widget. The result is that SWT applications tend to look and behave exactly like native applications on the system they are running on. No Java emulation is done at all, except if no native API will satisfy the needs of the SWT API. Thus, if a platform does not provide a tree widget, SWT will implement an emulated tree widget in Java.

SWT does not make use of AWT or any other Java tool kit to implement its functionality. SWT also makes minimal use of Java class libraries, thus allowing it to be run with older JDKs or restricted class libraries on handheld computers. Implementations of SWT are currently available on the following platforms:

  • Win32

  • Linux Motif and GTK

  • AIX Motif

  • HPUX Motif

  • MacOS Carbon

  • Photon

  • Pocket PC

FAQ 134: Why does Eclipse use SWT?

IBM’s first-generation Java development environment, VisualAge for Java, was written in Smalltalk, using an in-house implementation of the language and an in-house virtual machine and widget toolkit. The purpose of the Smalltalk widget toolkit, called Common Widgets (CW), was to provide a thin set of common APIs for building Smalltalk GUIs that run on a broad variety of platforms, implemented using the native widgets available on each platform.

When the decision was made in 1998 to use Java as the implementation language for the next generation of tools, the brand new Swing toolkit was initially evaluated as a GUI toolkit. However, the design philosophy of Swing was based on a strategy of implementing widgets in Java rather than leveraging the native widgets provided by each platform. Based on their experience with Smalltalk, the Eclipse development team believed that native look, feel, and performance were critical to building desktop tools that would appeal to demanding developers. As a result, the team applied the technology they had built for Smalltalk to build SWT—a platform-independent widget API for Java implemented using native widgets.

As this Java tooling framework evolved into what is now called Eclipse, new reasons emerged for choosing SWT as the widget set. Eclipse was designed from the start as an integration platform; a fundamental goal was to provide a platform that integrated seamlessly with other user applications. SWT, with its native widgets, was a natural choice. SWT applications look and respond like native apps, and have tight integration with such operating system features as the clipboard, drag-and-drop, and ActiveX controls on Windows. To this day, many people getting their first glimpse of an Eclipse-based product don’t believe that it is written in Java. It is difficult to differentiate from, and smoothly integrates with, other native applications on each of its target operating systems. The question then becomes, Why shouldn’t Eclipse use SWT?

A major downside of SWT in the past was that it was not very compatible with Swing-based applications. This was a strike against Eclipse’s primary goal as a tool-integration platform as companies with existing Swing-based applications were faced with the extra overhead of porting to SWT if they wanted to integrate cleanly with Eclipse. This was exacerbated by the fact that, as a new technology, few skilled SWT developers were in the market, and companies were reluctant to bet their tooling strategy on such an unknown quantity. As SWT has gained popularity, building a large community of developers and improved training and support, this has become less of an issue. In Eclipse 3.0, the final hurdle is coming down. There is now support for interoperability between SWT and Swing, as will be discussed in FAQ 144.

Note

FAQ 134: Why does Eclipse use SWT?

FAQ 144 How do I embed AWT and Swing inside SWT?

FAQ 135: Is SWT platform-specific?

If you are asking about the implementation of SWT, the answer is yes. In fact, the implementation of SWT is the only part of Eclipse that is platform specific. Several plug-ins have platform-specific add-ons, but they are largely optional. Ninety-nine percent of the task of porting Eclipse to a new platform consists of porting SWT to the new platform.

The SWT APIs, on the other hand, are largely platform independent. To be more specific, all classes in the SWT packages not marked internal are guaranteed to be binary compatible across all platforms supported by SWT. Thus, if you write a Java application on SWT, you can compile it into JARs on one platform to run on all platforms supported by SWT without linkage errors. The exceptions to this binary-compatibility rule are packages whose names end with the windowing system name. For example, the package org.eclipse.swt.ole.win32 is implemented only on Win32 platforms. Thus, most applications built on SWT obey the general Java credo of “write once, run anywhere.”

Yet another angle on the platform-specific question is to ask whether the behavior of SWT is platform specific. You may have noticed the careful wording of the binary-compatibility promise, which guarantees only that you will have no linkage errors when changing to another platform. SWT does not promise consistent behavior across platforms. On each platform, SWT instead strives for behavior that is consistent with other applications on that platform. Thus, an SWT application on Windows should behave like other Windows apps, and the same SWT application on Motif should behave like other Motif apps. As most Java developers know, the goals of cross-platform consistency and platform integration are not always compatible. SWT attempts to meet both goals, but where these aims are mutually exclusive, it will opt for platform integration over cross-platform consistency.

Thus, although you don’t have to worry about recompiling your application for every platform you want to support, it is a good idea to test your application on several platforms. On some platforms, subtle bugs emerge that do not appear on others owing to the vagaries of the platform’s native widgets. In rare cases, this cross-platform brittleness needs to be worked around by tweaking your application code. The only reliable way to manage these subtle differences is to test early and test often on all platforms you are interested in supporting.

FAQ 136: Is SWT better than Swing?

This is equivalent to asking whether a hammer is better than a screwdriver. The answer, of course, depends on whether you are holding a nail or a screw.

SWT and Swing are different tools that were built with different goals in mind. The purpose of SWT is to provide a common API for accessing native widgets across a spectrum of platforms. The primary design goals are high performance, native look and feel, and deep platform integration. Swing, on the other hand, is designed to allow for a highly customizable look and feel that is common across all platforms.

The answer to which is better for your application depends on which of these trade-offs you and your customers prefer. Do you want an application that looks the same on all platforms or one that looks and behaves like other applications on each of the platforms it is running on?

Of course, a hammer wielded with sufficient force can probably drive a screw into a wall, and the butt of a screwdriver can be used in a pinch to knock in a nail. However, a good carpenter keeps both hammers and screwdrivers in her tool box and will use the tool that is appropriate for the job at hand.

Note

FAQ 136: Is SWT better than Swing?

FAQ 144 How do I embed AWT and Swing inside SWT?

FAQ 137: Can I use SWT outside Eclipse for my own project?

This can be interpreted as either a legal question or a technical question. You can find an official answer to the legal question on the SWT FAQ hosted on the SWT development team home page at eclipse.org. The answer to the technical question is an unqualified yes! However, because SWT has a native component, the technical details are a bit more involved than they are for simple Java libraries.

Each platform you want your project to run on will need its own native libraries. Luckily, this is easier than it used to be because the download section of eclipse.org now includes SWT drops. Download the appropriate SWT drop for the platform you are interested in running on, and set up the VM’s classpath and library path accordingly. Here is a command line that was used to launch the BrowserSnippet stand-alone program:

java -cp swt.jar;. -Djava.library.path=. BrowserSnippet

This command line assumes that java is on your execution path and that both swt.jar and the SWT dynamic link library are located in the current working directory.

Note

FAQ 137: Can I use SWT outside Eclipse for my own project?

FAQ 23 How is Eclipse licensed?

FAQ 143 How do I display a Web page in SWT?

FAQ 138: Are there any visual composition editors available for SWT?

Several free and commercial products provide visual composition editors, or GUI builders, for SWT. These tools are especially appealing to people who are not yet skilled in all the intricacies of the SWT layout mechanisms and do not yet know what kinds of widgets are available to choose from.

After doing an informal poll, we discovered that none of the respondents in the Eclipse development team uses a visual builder to implement Eclipse. The UI for Eclipse is written manually in SWT, using an additional UI framework called JFace to take care of some of the repetitive aspects of writing UIs. Furthermore, when defining a new dialog, the developers often use the “Monkey see, monkey do” rule: They first find one that is close to the intended result; then, the new UI is cloned from the inspiration source and modified until it fits the needs of the new application.

With the growing popularity of SWT, more and more developers want to prototype and develop user interfaces with SWT. Visual builders help less experienced developers by eliminating most of the guesswork from the UI design labor. Widgets can be selected from a panel, and attributes can be chosen and assigned values from a limited set of options. The most successful builders offer fully synchronized views of the UI being developed and the generated source code to implement the UI.

Visual builders have been a long time coming for SWT, but a number of free and commercial GUI builders are finally available. The following is a brief listing of the free plug-ins we know about:

  • The Eclipse Visual Editor ProjectThe goal of this Eclipse project is to build a framework for creating Eclipse-based GUI builders. This project follows the general Eclipse philosophy of creating a platform- and language-independent framework, with language- and platform-specific layers on top. This project aims to provide Java-based reference implementations of SWT and Swing GUI builders. The project has not yet produced a stable release, but pre-1.0 versions are available.

  • V4ALL Assisi GUI–BuilderThis SourceForge GUI builder project targets both SWT and Swing. So far, it is the work of a single developer, and there does not appear to be much activity on it.

  • JellySWT (jakarta.apache.org/commons/sandbox/jelly/jellyswt.html)Jelly is a scripting engine that uses XML as its scripting language. The goal of JellySWT is to allow you to describe a UI by using Jelly script and then have it generate the Java code automatically. The idea is that it takes care of the tedious layout code for you. This isn’t really a visual composition editor, but it is a GUI builder of sorts.

The following are known commercial plug-ins:

  • SWT designer (swt-designer.com)This commercial plug-in to Eclipse, which targets only SWT, is fairly new as a commercial product but is based on an open source project that has been around for a while and has a strong following.

  • SWT GUI Builder (www.swtguibuilder.com)This commercial plug-in provides a visual editor for SWT only. The company also sells a product called Swing2SWT that ports Swing applications to SWT.

  • Jigloo GUI Builder (cloudgarden.com/jigloo)This fairly new GUI builder for both SWT and Swing is a commercial product, but a free version is licensed for noncommercial use only.

As with most listings of Eclipse plug-ins, this list will probably be outdated by the time this book goes to print. Check the plug-in listings in FAQ 9 for a more up-to-date list.

Note

Jigloo GUI Builder (cloudgarden.com/jigloo).

FAQ 9 What open source projects are based on Eclipse?

FAQ 139: Why do I have to dispose of colors, fonts, and images?

This question was asked so often that the SWT team wrote an article to explain why. The eclipse.org article “Managing Operating System Resources,” by Carolyn McLeod and Steve Northover, can be found in the articles section at eclipse.org. The article describes SWT’s philosophy on resource management and defends its reasons for not relying on the Java garbage collector for disposing of unused resources. The philosophy, in short, is this: If you create it, you dispose of it. The capsule summary of the reasoning is that the specification for Java finalization is too weak to reliably support management of operating system resources. This is also why database connections, sockets, file handles, and other heavyweight resources are not handled by the Java garbage collector. If you are still not convinced, read the article.

Note

FAQ 139: Why do I have to dispose of colors, fonts, and images?

FAQ 154 How do I use image and font registries?

FAQ 140: Why do I get an invalid thread access exception?

On most operating systems, drawing to the screen is an operation that needs to be synchronized with other draw requests to prevent chaos. A simple OS solution for this resource-contention problem is to allow drawing operations to occur only in a special thread. Rather than drawing at will, an application sends in a request to the OS for a redraw, and the OS will, at a time it deems appropriate, call back the application. An SWT application behaves in the same way.

When the end user of your application activates a menu or clicks a button, the OS will notify SWT, which in turn will call anyone listening to that button, until eventually the call chain ends with you. All these calls are made in the same event loop thread. Normally, a UI does not act on its own but reacts to stimuli from others. In general, GUI applications are passive.

Therefore, when an application decides that it needs to live a life on its own, one option is for it to create another Java thread. A typical sample is the following:

new Thread(new Runnable() {
   public void run() {
      while (true) {
         try { Thread.sleep(1000); } catch (Exception e) { }
         Display.getDefault().asyncExec(new Runnable() {
            public void run() {
               ... do any work that updates the screen ...
            }
         }
      }
   }
}).start();

This starts a timer that goes off every second and does some work. Because the work will be done in an unsafe thread, we need to request that SWT performs the task in a safe manner. We do this by requesting that the default SWT display runs our runnable when it can using asyncExec. In practice, this request is served as soon as possible. Execution is performed asynchronously. In other words, the request is placed in a queue with all other asyncExec requests and dealt with in a first-come first-served manner.

The call to Display.asyncExec returns immediately, before the drawing takes place. If you need to be guaranteed that the changes to the display took place before continuing, use Display.syncExec, which will suspend execution of the calling thread until the operation has finished.

Just about any SWT method that accesses or changes a widget must be called in the UI thread. If you are unsure, check the method javadoc. Any method that must be called in the UI thread will declare that it throws SWTException with value ERROR_THREAD_INVALID_ACCESS.

Avoid long-running processes in the UI thread as they will make the UI unresponsive. Do work that does not require UI access in a separate thread, and use the asyncExec call only for UI updates.

Note

FAQ 140: Why do I get an invalid thread access exception?

FAQ 127 Does the platform have support for concurrency?

FAQ 187 Can I make a job run in the UI thread?

FAQ 141: How do I get a Display instance?

Most users deploy Eclipse as one top-level window and manage their code in perspectives, explorers, editors, and views. However, SWT has been designed to optionally control a multitude of displays wherever this is allowed by the local operating system. The implication is that when creating something like a dialog window, SWT needs to be told what display to use for creating the dialog’s frame. Ideally, your application should keep its own references to the display where it is needed, but if for some reason you don’t have an instance, you have two ways to find one. The first way is by calling Display.getCurrent. A display is forever tied to the thread that created it, and a thread can have only one active display; a display is active until it is disposed of.

If you call Display.getCurrent, it returns the display that was created in that thread, if any. Here is an example:

public static Display getDisplay() {
   Display display = Display.getCurrent();
   //may be null if outside the UI thread
   if (display == null)
      display = Display.getDefault();
   return display;
}

A calling thread that does not have an active display will return null. Therefore, this method is useful only when you are absolutely certain that you are in the thread that created the display. This brings us to the second way you can obtain a display instance: Display.getDefault(). It will return the first display that was created. If your application has only one display, this is an acceptable way of obtaining the display.

Note

FAQ 141: How do I get a Display instance?

FAQ 140 Why do I get an invalid thread access exception?

FAQ 142: How do I prompt the user to select a file or a directory?

SWT provides native dialogs for asking the user to select a file (FileDialog) or a directory (DirectoryDialog). Both dialogs allow you to specify an initial directory (setFilterPath), and FileDialog also allows you to specify an initial selection (setFileName). Neither of these settings will restrict the user’s ultimate choice as the dialogs allow the user to browse to another directory regardless of the filter path. FileDialog also allows you to specify permitted file extensions (setFilterExtensions), and the dialog will not let the user select a file whose extension does not match one of the filters. The following example usage of FileDialog asks the user to open an HTML file:

FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.html"});
dialog.setFilterPath("c:\temp");
String result = dialog.open();

By default, FileDialog allows the user to select only a single file, but with the SWT.MULTI style bit, it can be configured for selecting multiple files. In this case, you can obtain the result by using the getFileNames method. The returned file names will always be relative to the filter path, so be sure to prefix the filter path to the result to obtain the full path.

Note

FAQ 142: How do I prompt the user to select a file or a directory?

FAQ 308 How do I prompt the user to select a resource?

FAQ 143: How do I display a Web page in SWT?

In Eclipse 3.0, SWT introduced a browser widget for displaying a native HTML renderer inside an SWT control. Prior to the introduction of this browser, it was necessary to invoke an external Web browser program for displaying rendered HTML. The browser can be instructed to render either a URL or a supplied string containing HTML content. The browser widget does not include the usual controls for navigation, bookmarks, and all the usual bells and whistles associated with a Web browser. As such, it can be used for highly controlled applications, such as displaying help text or even for showing decorated and interactive text inside a view or an editor.

The browser has API for programmatically manipulating the content, such as browsing forward or back in the navigation history, refreshing the content, or halting a rendering in process. You can install listeners on the browser to be notified when the location is changing or when the title changes or to receive progress notification as a page loads. It is fairly straightforward to implement basic Web browser functionality around this browser widget. For more details, take a look at BrowserAction in the org.eclipse.faq.examples plug-in. This action implements a fully functional Web browser in fewer than 60 lines of code!

For a richer example, look at the org.eclipse.ui.examples.browser project in the Eclipse repository (dev.eclipse.org). This project implements a Web browser as a stand-alone Eclipse RCP application. As a quick example, here is a stand-alone SWT snippet that opens a browser shell on this book’s Web site.

A title listener is added to the browser in order to update the shell title with the name of the Web page being displayed:

Display display = new Display();
final Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
browser.addTitleListener(new TitleListener() {
   public void changed(TitleEvent event) {
      shell.setText(event.title);
   }
});
browser.setBounds(0,0,600,400);
shell.pack();
shell.open();
browser.setUrl("http://eclipsefaq.org");
while (!shell.isDisposed())
   if (!display.readAndDispatch())
      display.sleep();

Figure 7.1 shows the resulting browser inside a simple shell. The browser widget is not yet available on all platforms as not all platforms that SWT supports have an appropriate native control that can be exploited. For Eclipse 3.0, the browser will at least be available on Windows, Linux, QNX, and MacOS. For platforms that do not have a browser widget available, the Browser constructor will throw an SWT error, allowing you to catch the condition and fall back to an alternative, such as a user-specified external browser.

SWT browser widget

Figure 7.1. SWT browser widget

FAQ 144: How do I embed AWT and Swing inside SWT?

In Eclipse 3.0, APIs have been introduced for integrating AWT and Swing with SWT. This support is “product-quality” on Windows and has only early access support on Linux under JDK 1.5. The main entry point for AWT integration is the class SWT_AWT. It provides a factory method, new_Frame, that creates an AWT Frame that is parented within an SWT Composite. From there, you can create whatever AWT components you want within that frame. The bridging layer created by SWT_AWT handles forwarding of SWT events to the corresponding AWT events within the frame.

Note

FAQ 144: How do I embed AWT and Swing inside SWT?

FAQ 136 Is SWT better than Swing?

FAQ 145: Where can I find more information on SWT?

BooksBefore 2004, comprehensive information on SWT was not available outside the SWT source code and javadoc itself. This situation changed in 2004 with the publication of SWT: The Standard Widget Toolkit in the Addison-Wesley Eclipse Series. This book was written by Steve Northover and Mike Wilson, two of the original architects and developers of SWT. When the acronym first appeared, it was jokingly referred to as Steve’s Widget Toolkit. Nobody knows SWT better than these authors, and their book is the most authoritative guide to the subject. If you’re doing extensive development using SWT, it’s indispensable. Volume 2 of their book is forthcoming.

Several other Eclipse books include a chapter or more on SWT:

  • Eric Clayberg and Dan Rubel, Eclipse: Building Commercial-Quality Plug-ins (Addison-Wesley, 2004), Chapter 4.

  • Erich Gamma and Kent Beck, Contributing to Eclipse (Addison-Wesley, 2004), Chapter 34.

  • Sherry Shavor, et al., The Java Developer’s Guide to Eclipse (Addison-Wesley, 2004), Chapter 14.

  • Rob Warner and Robert Harris, The Definitive Guide to SWT and JFace, (Apress, 2004), major part of book.

Web sitesThe information hub for SWT is the SWT development team home page (http://eclipse.org/swt). The main page has a basic SWT overview, and the Development Resources page has loads more information, including a comprehensive library of stand-alone SWT programs—called snippets—illustrating many of the important concepts in SWT. This page also hosts the official SWT FAQ maintained by the SWT development team, as well as development plans, platform porting status, and much more.

Visit www.cs.umanitoba.ca/~eclipse, hosted by the computer science department of the University of Manitoba, for extensive tutorials on using SWT, from a simple introduction to advanced applications. This site has a lot of high-quality information that can help you write your first stand-alone SWT application.

The home page for the SWT and JFace portion of the Eclipse wiki (www.eclipse-wiki.info) has links to other resource pages, but some information is here, along with a collection of FAQs.

The site www.swtworkbench.com is hosted by a company that does consulting and develops commercial SWT products. Its community page has discussion forums, news, links, and more, with a particular emphasis on SWT.

ArticlesThe first place to look for articles is the articles page on eclipse.org. We won’t bother listing all the articles here as the list would probably be stale by the time this book goes to print. Of particular note is the two-part article entitled “SWT: The Standard Widget Toolkit.” These articles were written by the SWT development team to describe some of the design rationale behind the project. The CD included with this book has PDF versions of all the articles, captured in May, 2004.

IBM developerWorks (www.ibm.com/developerworks) also has some technical articles focusing on SWT: “Using JFace and SWT in stand-alone mode,” and “How to Deploy an SWT application using Java Web Start.”

Discussion forumsThe main forum for discussion of SWT is the eclipse.platform.swt newsgroup. This is the place to go for all kinds of SWT questions for users of all levels, from novices taking their first steps with SWT to highly experienced SWT developers. The SWT develoment team regularly reads this newsgroup, so you can be sure of authoritative answers. Be sure to do a quick search (http://eclipse.org/search), before posting, to avoid asking a question that’s been asked before.

The platform-swt-dev mailing list is for discussion among members of the SWT development team and other contributors to SWT. If you are fixing SWT bugs, porting SWT to another platform, or looking for solutions to advanced questions that have not been answered on the newsgroup, you are welcome to ask here. SWT users are welcome to subscribe and follow along with the discussion, but to avoid cluttering the developer list, please use the newsgroup for your questions.

Some other Java forums have been known to host discussion threads on SWT. Unfortunately, these forums can sometimes deteriorate into flame wars on Swing versus SWT. One notable example is www.javalobby.org, which has had several SWT discussion threads.

Note

Discussion forums.

FAQ 13 What Eclipse newsgroups are available?

FAQ 15 What Eclipse mailing lists are available?

FAQ 16 What articles on Eclipse have been written?

FAQ 17 What books have been written on Eclipse?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.147.77