< Zurück | Inhalt | Weiter >

17.2.6 “Hello, world” SWT Style

SWT consists mainly of classes that represent controls—such as buttons, text areas, scrollbars, and so on—and layout managers which are much like layout managers in Swing. But there are two other classes: Display, which models the interface between your Java application and the underlying windowing system, and Shell, which effectively represents a single window.

The application in Example 17.1 is a parallel to the simple Swing program in the last chapter (Example 16.1).

This simple program, like its parallel in the Swing chapter, is deceptive. Sure, this is a lot of code to say “Hello, world” but it is because what we are setting up here is an event-driven program that must respond to any valid user input.


17.2.6.1 Setting Up to Run an SWT Application

One advantage of Swing that we haven’t pointed out up to now is that it is part of every Java runtime (well, not gcj; more on that later), so you have all the classes on your classpath without any special setup. Not so with SWT. The exact procedure for setting up to run an SWT application depends on what development environment you are using.

There is an excellent set of directions for running an SWT application under Eclipse in the SWT FAQ.8 No matter what your environment is, there is a basic series of steps:

1. Download the Eclipse SDK.

2. Install it.



image

8. http://dev.eclipse.org/viewcvs/index.cgi/~checkout~/platform-swt-home/ faq.php?rev=1.83content-type=text/html#standalone. Note that this link is to the current revision in CVS as of this writing. You should take a look at the parent page to see if there is a newer revision.


image

Example 17.1 A simple SWT application

import org.eclipse.swt.*;

import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*;


/**

* @author mschwarz

*

* Sample SWT "Hello, world" application

*/

public class SWTHelloWorld {


public static void main(String[] args) { Display disp = new Display();

Shell window = new Shell(disp); window.setLayout(new RowLayout());

Label label = new Label(window, SWT.NONE); label.setText("Hello, world."); window.setSize(320,160);

window.open();


while (!window.isDisposed()) { if (!disp.readAndDispatch()) {

disp.sleep();

}

}


disp.dispose();

}

}


image


3. Extract the SWT JAR files.

4. Extract the SWT JNI files.

5. Configure your development environment.

Let’s go over these in a bit more detail.

SWT was developed as a GUI library for the Eclipse project. It is distribut- ed as part of Eclipse. There is no official standalone SWT package. The right way to obtain SWT is to download and (at least temporarily) install the Eclipse SDK. See Section 10.4 for details.



image

Figure 17.1 Running the SWT version of “Hello, world”


If you have followed our sage advice and downloaded the GTK version of the Eclipse SDK, then you need to copy out the SWT JAR files. There are two files in the GTK version, and just one in the Motif version. The GTK version’s files are swt.jar and swt-pi.jar. They are both in the eclipse/plugins/org.eclipse.swt.gtk_2.1.2/ws/gtk directory. You will need to have both of these JAR files on the classpath of any SWT application you are compiling or running.

Remember that SWT is a JNI library. You must also have the native Linux shared libraries. These need to be made available to the Java native loader. The files you need are located in the eclipse/plugins/org.eclipse.swt. gtk_2.1.2/os/linux/x86 directory. The .so files there must be available to any running SWT application. There are a couple of ways to do this. First, as described in Section 5.7, you can set the LD_LIBRARY_PATH environment variable. You also can use the -D parameter for the runtime VM to set the java.library.path property.

If you want to, you can copy these files out of the eclipse directory to some other location and then erase the eclipse directory with the lovable old standby, rm -rf eclipse.

Oh, by the way, once you have compiled the sample code above and set your classpath and Java library path correctly, running the application produces the window shown in Figure 17.1.


17.2.6.2 Anatomy of an SWT Application

Before we launch into this discussion, we should point out that the Javadoc documentation for all SWT packages is available as part of the Eclipse Platform


documentation.9 You might want to use that resource along with this lightweight tutorial to fill in the gaps and shortcuts.

It should not be too surprising that there are similarities between SWT, AWT, and Swing. They all take different approaches to solving the same problem, namely how to control the complexity of a graphical event-driven application. Because the problem is the same, there can’t help but be similarities between different solutions. By now you may have deduced that the Shell class is an analog to the JFrame class, and that SWT uses a system of layout managers not too different from Swing. If so, you are on the right track and well on your way to using SWT.

If we had to summarize the difference in approaches between SWT and Swing, it would be that SWT tries to provide a small number of complex classes, and Swing tries to provide a large number of simpler classes. Obviously, this is a generalization, but everybody generalizes. Sorry.

The Display is a class that provides the link to the underlying GUI sys- tem. Think of it as an abstraction of the interface to the windowing system. In almost all cases, an SWT application will have exactly one instance of Display. The Shell class represents a window. This class descends from a series of abstract parent classes, so if you look at the Javadoc for Shell and think it is simple, be sure to drill down into those parent classes! We’ll discuss Shell quite

a bit more as we go along.


17.3 PORTING BUDGETPRO TO SWT


The conversion of an existing application is a complex process. Always consider rewriting from scratch. Still, it is worthwhile to show an application converted from Swing to SWT, because it will emphasize the relationship between the two.

We begin with the reobjecting. Starting with the BudgetPro class, we need to add an instance of the Display class. Then the JFrame becomes a Shell. Likewise, the JLabels become Labels. Then . . . Wait a minute. You don’t need a blow-by-blow account. Maybe it would be simpler to show you what SWT classes roughly correspond to the equivalent Swing classes (Table 17.1).


image

9. http://download.eclipse.org/downloads/documentation/2.0/html/plugins/ org.eclipse.platform.doc.isv/reference/api/


Table 17.1 Major SWT widgets and their Swing equivalents


image

SWT widget


image

Button


Canvas


Caret Combo


Composite


Group


Label


List


Menu


MenuItem


ProgressBar


Scale


ScrollBar

Analogous Swing component


JButton


java.awt.Canvas, but see also

java.awt.Graphics2D javax.swing.text.Caret JComboBox


JPanel


JPanel


JLabel


JList

JMenu JMenuItemA,

JCheckboxMenuitem,

JRadioButtonMenuitem JProgressBar


JSpinner


JScrollPane

Description


Display widget that sends notification when pressed and/or released.

Composite widget that provides a surface for drawing arbitrary graphics. May be used to create custom widgets.

A cursor used as the insertion point for text.

Widget that permits the user to choose a string from a list of strings, or to enter a new value into a text field.

Widget that is capable of containing other widgets.

Composite widget that groups other widgets and surrounds them with an etched border and/or label.

Nonselectable widget that displays an image or a string.

Selectable widget to choose a string or strings from a list of strings.

User interface widget that contains menu items.

Selectable widget that represents an item in a menu.


Nonelectable widget that displays progress to the user.

Widget that represents a range of numeric values.

Widget that represents a range of positive numeric values. Used in a Composite that has V_SCROLL and/or H_SCROLL styles. The mapping to Swing is not very tight here, since JScrollPane is like a combination of Composite and ScrollBar.


image


Table 17.1 (Continued)


image

SWT widget


image

Shell


Slider


TabFolder


TabItem


Table


TableColumn


TableItem


Text


ToolBar


ToolItem


Tree


TreeItem

Analogous Swing component


JPanel


JSlider


JTabPane


Any JComponent JTable


JTableColumn

or instance of

TableColumnModel

TableCellRenderer or

TableCellEditor

JTextField, JPasswordField, JFormattedTextField, JTextArea, JEditorPane, JTextPane


JButton


JTree


MutableTreeNode

Description


Window that is managed by the OS window manager. A Shell may be a child of a Display or another shell.

Widget that represents a range of numeric values. Differs from a Scale by having a “thumb” to change the value along the range.

Composite widget that groups pages that can be selected by the user using labeled tabs.

Selectable user interface object corresponding to a tab for a page in a tab folder.

A selectable widget that displays a list of table items that can be selected by the user. Rows are items, columns are attributes of items.

Selectable widget that represents a column in a table.


Selectable widget that represents an item in a table.

Editable widget that allows the user to type text into it.


Composite widget that supports the layout of selectable toolbar items.

Selectable widget that represents an item in a toolbar.

A selectable widget that displays a hierarchical list of user-selectable tree items.

Selectable user interface object that represents a hierarchy of items in a tree.


image


We are going to walk you through converting only one of the GUI source files for the BudgetPro application. We will leave converting the rest as an exer- cise for you. We’ll talk about some of the entertaining differences between the models. As you shall see, there is no clear “winner” here between SWT and Swing. Almost all technical choices—SWT versus Swing, Java versus C++, Emacs versus vi, or for that matter UNIX versus Windows—are tradeoffs. This is no exception. There are things we like about SWT. For simple GUI applica- tions, we think it is easier to set up and use. We think it is easier to learn in its entirety than Swing. Swing, on the other hand, is more complete, offering classes that will do more than SWT. So the best solution depends (as always) on your requirements.