Java Reference
In-Depth Information
The next step is to convert the GUI members of the class from the Swing
classes to their SWT counterparts. Of course, SWT requires the Display class,
which has no analog in SWT, so we add a Display type member named disp
just ahead of the frame member.
Next, we change the type of frame from JFrame to Shell . We could re-
name the member, 10 but why add to our typing burden? The name is still clear
and meaningful, even if it doesn't match the SWT name. 11 There's more to it
than just changing the type, however. The constructor call for the JFrame
doesn't match any constructor for Shell . In fact, the Shell constructor re-
quires a Display object argument, and all subsequent constructors for widgets
and controls require a Composite as an argument.
This is a key difference between Swing and SWT. Swing allows you to
build GUI components in arbitrary order at arbitrary times and then join them
up to the GUI with an add() method call. SWT instead requires that you link
your components up to the GUI element they belong to when they are construct-
ed . There are good reasons for this difference. Remember that SWT allocates
native objects and memory that Java's garbage collector cannot recover. Because
of this, SWT makes the promise that if you call the dispose() method on any
SWT object, it will dispose of it and everything it contains. That allows you to
clean up all resources from an SWT program by calling dispose() on the top
level Display object. If SWT allowed you to build GUI structures indepen-
dently and then graft them onto the hierarchy, it could not keep this promise.
For this reason (amongst others) SWT objects are always built in a fairly rigid
top-down manner. 12
The most direct consequence of this is that we have to get rid of the con-
structors on these declarations. We'll start construction in the main() . So, away
with the constructors for the GUI elements. We now need to change the
JButton s to Button s and the JLabel s to Label s. Again, if you are using a
dynamic IDE, you should see your error count skyrocket with these changes
10. If you are using Eclipse, this is easily done throughout your code with the Refactoring
feature.
11. All right, I'm being lazy. Write your own book if you don't like it.
12. In some ways, this greatly simplifies SWT programs, but at the cost of some reusability.
With Swing, you could construct a panel or other GUI element and reuse it in many places.
You can achieve the same thing in SWT by encapsulating such a construct in its own class and
passing in a parent to the constructor, but this is a bit more bulky and complex than the
Swing way.
Search WWH ::




Custom Search