A control is an user-interface element that belongs to a higher-level window. In this section, we are going to describe some of the basic ones in detail, such as labels, texts, lists, layouts, buttons, and combos. These simple controls are commonly used when developing applications using the SWT. In the next chapter, we will extend this section with more advanced controls and examples.
Labels are static widgets that represent an object that cannot be modified or selected, and can act like a string, image, or separator. They are usually placed in the left-hand side of the screen to describe text fields, act as separators among non-related fields or to place an image.
The following styles can be selected when you create a label, and can be combined using the |
operator:
SWT.SEPARATOR
: Draws a separatorSWT.HORIZONTAL
: Draws the separator horizontallySWT.VERTICAL
: Draws the separator verticallySWT.SHADOW_IN
: Separator with shadow in effectSWT.SHADOW_OUT
: Separator with shadow out effectSWT.SHADOW_NONE
: Separator with no shadow effectSWT.CENTER
: Aligns the label to the centerSWT.LEFT
: Aligns the label to the leftSWT.RIGHT
: Aligns the label to the rightSWT.WRAP
: Automatically wraps the text to fit the containerThe main methods used when creating a label widget are:
setText(String string)
: Sets the text of the labelgetText()
: Returns the text of the labelsetImage(Image image)
: Sets an image to be included in the labelgetImage()
: Returns the image of the labelWe show a sample code of how to use a label, along with the widget representing it as follows:
Display display = new Display(); Shell shell = new Shell(display); shell.setText("Label Sample"); shell.setSize(300,200); Label label = new Label(shell, SWT.CENTER); label.setText("Nothing But The Rain"); label.setSize(300,300);
It bears mentioning that the inherited setSize
method takes as parameters an horizontal and a vertical size in pixels.
Text widgets are editable text fields for strings. These strings can comprehend one or more lines, and can be used for password fields. They are also selectable by an user.
The following are several styles available for the creation of a Text widget:
Text widgets support only plain text, which means that the characters must have the same font and size. If a more flexible text control is needed, one could use a StyledText
widget, which is not a native widget from SWT.
When using text fields in an SWT program, it is rather common that the widget will have some kind of functionality in the application. A programmer often needs to detect when a text has changed or to filter a string that is being typed. For this purpose, it may be necessary for listeners to handle the following text-control events:
DefaultSelection
: Enter is pressedModify
: Text is modifiedVerify
: Text is to be validatedOrientationChange
: Orientation is changedIn the following example we show how to deal with one of the mentioned events, SWT.Modify
. For that we create a Text
widget, and add a listener for the SWT.Modify
event. This event is sent when any character is entered by an user. The purpose of the code inside such listener is to count the number of characters that have been typed. A message is displayed in a label located underneath the Text
widget.
Display display = new Display(); Shell shell = new Shell(display); shell.setSize(200,200); final Text text = new Text(shell, SWT.CENTER | SWT.BORDER); text.setSize(200,25); final Label label = new Label(shell, SWT.CENTER); label.setLocation(0,100); label.setSize(200,25); text.addListener(SWT.Modify, new Listener() { public void handleEvent(Event event) { label.setText(Integer.toString(text.getText().length())); } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose();
The following screenshot shows the GUI output related to this snippet of code:
It bears mentioning that in this example we also use the setSize
and setLocation
methods, that are respectively responsible for setting the size of the control and its location, by x
and y
coordinates in pixels. The pack()
method is also used to auto resize the widget to its preferred size.
Buttons are often used in desktop applications because these usually make use of the mouse device. When a user selects an option, it is possible to handle the selection event. Buttons can be filled with text or images, but not at the same time, and there is no option to obtain multiple lines of text on the screen.
The following styles are available when creating a Button
control:
ARROW
: Draws the button with arrow appearanceCHECK
: Checks button behaviorPUSH
: Pushes button behaviorRADIO
: Shows radio button behaviorTOGGLE
: Toggles button behaviorFLAT
: Draw the button with flat appearanceUP
: Draws an up arrowDOWN
: Draws a down arrowLEFT
: Draws a left arrow or aligns to the leftRIGHT
: Draws a right arrow or aligns to the rightCENTER
: Draws a center arrow or aligns to the centerThe only available event is the SWT.Selection
event, that is triggered when a button is clicked.
We show an example of how to use a Button
control, followed by the application output as follows:
Display display = new Display (); Shell shell = new Shell (display); Label label = new Label (shell, SWT.NONE); label.setText ("Enter your name:"); Text text = new Text (shell, SWT.BORDER); text.setLayoutData (new RowData (100, SWT.DEFAULT)); final Label resultLabel = new Label(shell, SWT.BORDER); resultLabel.setText("Nothing pressed"); Button ok = new Button (shell, SWT.PUSH); ok.setText ("OK"); ok.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { resultLabel.setText("OK pressed"); } }); Button cancel = new Button (shell, SWT.PUSH); cancel.setText ("Cancel"); cancel.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { resultLabel.setText("Cancel pressed"); } }); shell.setLayout (new RowLayout ()); shell.pack (); shell.open (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } display.dispose ();
In this example, we create two push buttons, namely OK and Cancel, and we add two listeners that are triggered when each button is pushed, showing the message OK pressed, or Cancel pressed. In a real-world application, a possible use of such application could be reading the name that was typed in the Text
widget for recording when the OK button is pressed.
A list can be used to show a set of selectable strings by the user. They are presented in a single column, and there are methods for selecting, adding, and removing items from it. The contents of a list can be set by the method setItems(String[] items)
. When you need to set or replace a specific item, it is possible to use setItem(int index, String item)
.
Similarly, to the setItem
method, this widget facilitates the achievement of one or more items from a list by using the getItem
or getItems
methods.
Items can also be added by the add
method, and removed using the remove
method.
The setSelection
and getSelection
methods are generally used when operations dealing with the selection of items need to be performed.
The following styles are available for a List
widget:
SINGLE
: Only one item can be selectedMULTI
: Multiple items can be selectedThe description of each style is pretty straightforward. We present the available events for this control as follows:
SWT.Selection
: An item is selectedSWT.DefaultSelection
: An item is double-clickedA code sample using the SWT.Selection
method is described, followed by the GUI outcome as follows:
Display display = new Display (); Shell shell = new Shell (display); final List list = new List (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); for (int i=0; i<10; i++) list.add ("Item " + i); list.setSize(200, 200); list.addListener (SWT.Selection, new Listener () { public void handleEvent (Event e) { String string = ""; int [] selection = list.getSelectionIndices(); for (int i=0; i<selection.length; i++) string += selection[i] + " "; System.out.println ("Selected: " + string); } }); shell.pack (); shell.open (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } display.dispose ();
In this example, we added 10 items to a list using the add method, and handled the event SWT.Selection
. When selecting those three items of our example, the application outputs the following string to the console: Selected: 2 4 5.
A Combo
widget, commonly known as combo box, is a combination of a Text
widget and of a List
one. The Combo
widget is generally displayed as a drop-down list when an user clicks on a small icon in the Combo
control.
It is possible for the user to type in the text field or to choose an item from the list, but if desired, the combo box can be set as read-only, where only the pre-defined item values can be selected.
The methods for the Combo
widget are a combination of the ones from the Text
widget together with the ones from the List
widget.
The following styles are available for the Combo
widget:
SIMPLE
: Combo always has a visible listDROP_DOWN
: Combo is a drop-down listREAD_ONLY
: Combo is non-editableThe available events for the Combo
widget are as follows:
DefaultSelection
: Item is double-clicked or Enter is pressedModify
: Text has been modifiedSelection
: Item is selectedWe show an example of how to use a combo box, followed by the GUI output.
Display display = new Display (); Shell shell = new Shell (display); Combo combo = new Combo (shell, SWT.SIMPLE | SWT.READ_ONLY); combo.setItems(new String [] {"Three", "Six", "Eight"}); combo.setSize(200, 50); shell.pack (); shell.open (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } display.dispose ();
In this example, a combo box is created using the simple style merged with the read-only one. Three items are added and no event is being handled.