Eclipse Tutorial, Part 02: Basic SWT Widgets
Eclipse Tutorial, Part 02: Basic SWT Widgets
by Shantha Ramachandran
Overview:
In this document, we describe the basic SWT (Standard Widget Toolkit) widgets. Our
focus is on developing Java applications that use the SWT, not on developing plugins to
extend the Eclipse workbench. If you have not already run an SWT-based application
using the Eclipse workbench, you should review the information on installing Eclipse and
setting up the SWT libraries in the previous document, Installing Eclipse.
Widget Structure:
To create an application that uses SWT widgets, you need to start by importing the
following packages:
org.eclipse.swt.*;
org.eclipse.swt.widgets.*;
A display is an object that contains all GUI components. A display is not actually visible
but the components added to a display are visible. Typically, only one display is created
for an application. A shell is a window within the application. There may be any number
of shells created for an application, with shells being at the top level (attached to a
display) or shells being attached to other shells.
1
This work was funded by an IBM Eclipse Innovation Grant.
2
© Shantha Ramachandran and David Scuse
shell.setSize(100,100);
Finally, you need to open the shell and run an event loop. This event loop is required for
the shell to visible on the screen. You can place it after any code you have initializing
widgets on the shell. When the shell is closed, the display must be disposed.
shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
Now, you are ready to add any widgets to your shell. We will not use a layout manager
for now, as creating widgets with a layout manager is a little more complicated. The
following examples all deal with placing widgets on a shell with no layout.
Label
A label is a collection of characters that can not be modified by the user (although the
characters can be modified by the programmer).
The different styles of labels are BORDER, CENTER, LEFT, RIGHT, WRAP and
SEPARATOR. The separator style is a special kind of label that draws a line separating
your other widgets. The styles that can be added for a separator are HORIZONTAL,
VERTICAL, SHADOW_IN, SHADOW_OUT and SHADOW_NONE.
The following code creates five labels, two of which are separators. The first text label
has a border, the second is a normal label, and the third has a colored background that
was set using the setBackground() method. The two separators in the example are
horizontal, but the first has a shadow style applied to it.
Text
A text widget contains text that can normally be modified by the user.
The text widget has some interesting properties that can be set. If your text is editable,
you can set the maximum number of characters that can be typed:
text1.setTextLimit(30);
You can also create password text boxes by using the setEchoChar() method. The
argument for this method is the character that is to be displayed in the text. The correct
string will still be in the text, but will only be viewed as a sequence of a specified
character:
text2.setEchoChar('*');
The following code creates three text widgets. The first one has a 30 character text limit.
The second one displays all text as a series of asterisks, much like a password field. The
final text has used the setEditable() method to make the control read only. Another way
to accomplish this would be to give it the style SWT.READ_ONLY.
Try running the following code and typing in the text widgets:
Button
A button is a widget that is clicked by the user in order to initiate some processing.
You can replace SWT.PUSH with any of the button types that SWT supports. This
includes PUSH, CHECK, RADIO, TOGGLE and ARROW. You can also use the styles
FLAT, BORDER, LEFT, RIGHT and CENTER with one of these types.
button1.setText("Hello");
In order for the button to be visible on the screen, you need to set the size and the location
of the button. Alternatively, you can set the bounds of the button and both the size and
the location will be set at once.
button1.setLocation(0,0);
button1.setSize(100,20);
You can also set the style, background, image and more by using set methods. To add an
event handler to your button, you first need to import the events package:
import org.eclipse.swt.events.*;
button1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Button1 was clicked");
}
});
Here is a small sample that incorporates all the code seen above. It creates a button
which, when clicked, will print “Button was clicked” to the console, an arrow button, and
a button with more than one style - toggle and flat.
A list is a widget that contains a collection of items; the user may select an item from the
list.
The different styles that a list supports are BORDER, H_SCROLL, V_SCROLL,
SINGLE and MULTI.
To add items to a list, you can use the setItems() method, or the add() method.
In the following example, two lists are created. The first list uses the H_SCROLL style to
create a horizontal scrollbar within the list. The second one uses a MouseListener to
respond to MouseDown and MouseUp events. The MouseListener works in a similar
fashion to the SelectionListener. A MouseAdapter is created with one of or both of
mouseUp() and mouseDown() methods. This is the code that is necessary:
list2.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
System.out.println(list2.getSelection()[0] +" wins");
}
public void mouseUp(MouseEvent e) {
System.out.println("Try again!");
}
});
Note that list2 must be declared as final in order to use it within the adapter:
Combo
A combo widget allows the user to select an item from a collection of items. The user
may also type a value into the combo widget.
The styles that are supported by Combo are BORDER, DROP_DOWN, READ_ONLY
and SIMPLE. More than one style can be used at a time, as in the above code.
To add items to a Combo, use the setItems() method. This takes a string array as an
argument.
Use the select() method to select one of the list items. This method takes an integer
argument - the index of the item to be selected.
The following example creates three Combos. The first is a drop down list whose
location and size are set. The second is a simple Combo whose location and size are set at
one time using the setBounds() method. The third is a Combo with no items.
Combo combo1 = new Combo(shell, SWT.DROP_DOWN|SWT.READ_ONLY);
combo1.setItems(new String[] {"One","Two","Three"});
combo1.select(0);
combo1.setLocation(0,0);
combo1.setSize(100,20);
Combo combo2 = new Combo(shell, SWT.SIMPLE);
combo2.setItems(new String[] {"Red","Green","Blue","Yellow"});
combo2.setBounds(50,50,200,150);
combo2.select(1);
Combo combo3 = new Combo(shell, SWT.DROP_DOWN);
combo3.setLocation(200,0);
combo3.setSize(50,50);
Composite
A composite is a widget that can contain other widgets. Widgets are placed inside a
composite in the same manner that widgets are placed on a shell. The position of each
widget inside a composite is relative to the composite, so if the composite is moved on
the shell, the widgets inside the composite retain their relative positions.
You can set properties of the composite, like background colour, but you cannot set a text
value.
The following code is an example of placing a composite within a composite. The first
composite has a border and a coloured background, so it is easily spotted on the screen.
In order to use the setBackground() method for any control, you need to import the
graphics library and create a color:
import org.eclipse.swt.graphics.*;
Color myColor = new Color(display, 0, 0, 0);
Note that if you do not give a composite a border or a background, you will not be able to
distinguish it from the rest of the shell. The second composite exists within the first. It
has horizontal and vertical scroll bars, and a list within the composite:
Composite composite1 = new Composite(shell,SWT.BORDER);
composite1.setBounds(10,10,270,250);
composite1.setBackground(new Color(display,31,133,31));
Label label = new Label(composite1,SWT.NONE);
Group
A group is also a widget that can contain other widgets. A group is surrounded by a
border and may, optionally, contain a title. As with composites, the position of each
widget inside a group is relative to the group, so if the group is moved on the shell, the
widgets inside the group retain their relative positions.
You can set all the standard properties for a group, such as size, location, background,
and more. However, the principal use of a group is to separate other controls into
sections. A group is a subclass of composite, and works in very much the same way. It
has additional functionality though, such as setting the text:
group1.setText("Group 1");
The following example only uses one group on the main shell, but has a second group
embedded within the first group. Since a group is a control as well as a composite, this is
allowable. You can have many nested groups to arrange numerous controls on a screen:
Group group1 = new Group(shell, SWT.BORDER);
group1.setBounds(30,30,200,200);
group1.setText("Group 1");
The widgets shown in this document were also run under Linux (GTK and Motif). Other
than some slight differences in appearance, we have not found any differences in
behaviour.
GTK Motif
Events:
In the earlier sections of this document, we introduced the Eclipse event structure by
defining listeners for buttons and a few other simple events. We now describe the
Eclipse event structure in more detail and create listeners for a variety of common events.
To capture events in SWT, you need to add listeners to your controls. Then when the
event corresponding to the listener occurs, the listener code will be executed.
In order to capture events in SWT, you need to do two things. First, you create a listener
specific to the event that you wish to capture. There is an interface for each listener that
you can use (ie. SelectionListener). There is also a class that will provide you with the
event information (ie. SelectionEvent). Within the listener that you create, you must
implement the methods defined in the interface.
SelectionListener listener = new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
System.out.println("Button Selected");
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
};
The second thing you need to do is add the listener to your widget. Each control has
methods to add listeners (ie. addSelectionListener()). You pass your listener to this
method, and you are all set to capture events.
button.addSelectionListener(adapter);
Now that we know how to add a listener to a widget, we will go over the more common
types of listeners. The most common type of listener is the selection listener, which we
have just seen. Some other important ones include key listeners and mouse listeners.
Key Listener
The KeyListener has two methods, keyPressed and keyReleased, whose functions are
obvious. The event object is KeyEvent. Because there are two methods, there is also a
KeyAdapter you can use to implement only one of the methods.
The KeyEvent is the more interesting feature of capturing key events. In most cases, if
you are using a key listener, you wish to know which key was pressed. The KeyEvent has
a property called character, which stores which character was just pressed. You can
access this character value using e.character (where e is the KeyEvent parameter). You
can also access the key code and state mask of the key that was pressed. The key codes
for special keys are constants in the SWT library, like SWT.CTRL for the control key
and SWT.CR for the carriage return key. The state mask indicates the status of the
keyboard modifier keys. The example at the end of this section demonstrates how you
can use the state mask.
Try this code out and see what kind of results you get from pressing various keys. Note
that if we used a KeyAdapter instead of a KeyListener, we would have only had to
implement one of keyPressed and keyReleased.
Mouse Listeners
There are three types of mouse listeners; MouseListener, which tracks pressing the
mouse, MouseMoveListener, which tracks when the mouse is being moved, and
MouseTrackListener, which tracks where the mouse is in relation to the control. We will
go over all three of these listeners. Since we are dealing with events, it is not possible to
show the results here, so make sure you try out the code, to see what kind of results you
get.
The fields in MouseEvent which are unique to the MouseListener are x, y, stateMask and
button. The button property returns the number of the button that was pressed or released.
So the first button on the shell would return a value of 1, the second would return 2, and
so on. The x and y properties return the location coordinates of the mouse at the time of
the event. The stateMask property returns the state of the keyboard modifier keys at the
time of the event.
The following example has two MouseAdapters. One of the adapters implements the
mouseUp and mouseDown methods. This adapter is attached to two different buttons. We
can do this by first creating the adapter, then adding it to whichever widgets need to use
it. We find the number of the button that has been pressed, and also the coordinates of the
mouse when it is both pressed and released. The other adapter implements the
mouseDoubleClick method. It opens a new window when the double click event it
created on the Label:
Try this code out. Note that if you press on the first button, it tells you that Button 1 has
been pressed, and pressing on the second button tells you that Button 2 has been pressed.
If you press your mouse down, move it around, and then release it, you will see the
different coordinates that your mouse was pressed and released at.
The MouseMoveListener has one method, mouseMove. This method is invoked when the
mouse is moved over the control onto which it is attached. The event generated is a
MouseEvent again.
The following example illustrates how to use both the mouse move listener and the
mouse track listener. The first canvas has a mouse move listener attached to it. When you
move the mouse over top of the canvas, the colour of the canvas changes. The second
canvas has a mouse track listener attached to it. When your mouse enters over top of the
canvas, a number is displayed in the canvas. Each time you hover your mouse over the
canvas, the number is increased. When the mouse leaves the area of the canvas, the
number disappears and starts at zero again when the mouse re-enters the area.
Note that in order to change a control within a listener, it must be declared as a final
variable. Run this code and see what kind of results you get by generating mouse events
on the controls.
Text Listeners
There are a couple of listeners that are useful when using Text widgets. These are the
ModifyListener and the VerifyListener. The ModifyListener is called when text is
modified, and the VerifyListener is called before text is modified. This one can be used to
verify that the new values being entered are valid. We will briefly go over both of these
listeners.
ModifyListener
The ModifyListener has one method, modifyText. The event object is a ModifyEvent.
This event is similar to a TypedEvent, and has fields such as time and widget.
VerifyListener
The VerifyListener has one method, verifyText. The event object is a VerifyEvent. This
event has all the properties of a TypedEvent and a KeyedEvent, as well as the fields start,
end, doit and text. The start and end properties indicate the range of text which is about to
be modified. The text variable indicates the new text to which your text is being changed.
The doit flag indicates whether or not we should complete the action that triggered the
event.
We can use the VerifyListener to check and make sure certain characters can be entered
in specific fields. In the following example, we check to see if the user is entering an
asterisk in the text. If so, the action is cancelled. Notice that no matter how many times
the ‘*’ key is pressed, no asterisks will appear in the text.
Focus Listeners
This section deals with FocusListener and TraverseListener. The FocusEvent is generated
when a widget receives focus, by any means. A TraverseEvent is generated when a
widget gains focus by means of traversal. We will cover both kinds of event handlers.
FocusListener
The FocusListener has two methods, focusGained and focusLost. They are called at
obvious times. The event generated is a FocusEvent. This event has all the properties of a
TypedEvent. See the example at the end of this section for more details.
The TraverseListener has one method, keyTraversed. This is called when the widget the
handler is attached to is traversed by a traversal method, such as tabs or up and down
arrows.
The event generated is a TraverseEvent. Some useful properties of this event object are
detail and doit. The doit property is the same as for the VerifyListener; it sets a flag
indicating whether the event should continue. The detail property indicates what kind of
traversal generated the event. These traversals can all be referred to by using
SWT.TRAVERSE_XXXX.
In the following example, you can see we compare the detail in the TraverseEvent with
SWT.TRAVERSE_TAB_PREVIOUS. If the traversal was a previous tab, we cancel the
action.
b1.addFocusListener(focusListener);
b4.addTraverseListener(traverseListener);
b4.addFocusListener(focusListener);
b6.addTraverseListener(traverseListener);
A project that contains the examples used in this document is available in a zip file
format. In order to make it possible to run each demo from a main shell, the instructions
used to create each demo had to be modified because Eclipse does not permit an
application to create more than one display.
To run a demo program by itself, a display is created at the beginning of the run method.
If the method may be called either by the demo program itself or by an external
supervisory routine, the following changes must be made to the program structure.
Summary:
We have examined only the basic widgets, some of their common properties, and the
basic event structure in this document. For more information on each widget, review the
Eclipse API documentation at:
http://download.eclipse.org/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/