Widgets in Java SWT

In this part of the Java SWT programming tutorial, we will introduce some SWT widgets.

Widgets are basic building blocks of a GUI application. Think of widgets as parts of a lego. Over the years, several widgets became a standard in all toolkits on all OS platforms. For example a button, a check box or a scroll bar.

Label

Label is a non-selectable user interface object that displays a string or an image. In addition, it can display a horizontal or vertical line.

LabelEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program uses the Label widget to
 * show lyrics of a song.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class LabelEx {

    final String lyrics =
"And I know that he knows I'm unfaithful\n"+
"And it kills him inside\n"+
"To know that I am happy with some other guy\n"+
"I can see him dyin'\n"+
"\n"+
"I don't wanna do this anymore\n"+
"I don't wanna be the reason why\n"+
"Every time I walk out the door\n"+
"I see him die a little more inside\n"+
"I don't wanna hurt him anymore\n"+
"I don't wanna take away his life\n"+
"I don't wanna be... A murderer";

    public LabelEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {

        Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        Label label = new Label(shell, SWT.LEFT);
        label.setText(lyrics);

        Point p = label.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        label.setBounds(5, 5, p.x+5, p.y+5);

        shell.setText("Unfaithful");
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        LabelEx ex = new LabelEx(display);
        display.dispose();
    }
}

The code example shows some lyrics on the window.

    String lyrics =
"And I know that he knows I'm unfaithful\n"+
"And it kills him inside\n"+
...

We build a multiline text.

Label label = new Label(shell, SWT.LEFT);
label.setText(lyrics);

The Label widget is created; the SWT.LEFT option makes its text is left aligned.

Point p = label.computeSize(SWT.DEFAULT, SWT.DEFAULT);
label.setBounds(5, 5, p.x+5, p.y+5);

We compute the size of the text in order to put some space round the text.

shell.pack();

The pack() method sizes the window to its preferred size; big enough to display the label widget.

Check button

In SWT, a check button is a special case of a Button. It is a widget that has two states: on and off. The on state is visualised by a check mark. It is used to denote some boolean property.

CheckButtonEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program uses a check button
 * widget to show/hide the title
 * of the window.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class CheckButtonEx {
    
    private Shell shell;

    public CheckButtonEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {

        shell = new Shell(display);

        RowLayout layout = new RowLayout();
        layout.marginLeft = 30;
        layout.marginTop = 30;
        shell.setLayout(layout);

        Button cb = new Button(shell, SWT.CHECK);
        cb.setText("Show title");
        cb.setSelection(true);
        
        cb.addListener(SWT.Selection, event -> onButtonSelect(cb));

        shell.setText("Check button");
        shell.setSize(250, 200);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    private void onButtonSelect(Button cb) {

        if (cb.getSelection()) {
            shell.setText("Check button");
        } else {
            shell.setText("");
        }        
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        CheckButtonEx ex = new CheckButtonEx(display);
        display.dispose();
    }
}

The window's title is displayed depending on the state of the check button.

Button cb = new Button(shell, SWT.CHECK);
cb.setText("Show title");

The check button widget is created by passing the SWT.CHECK to the Button constructor. The setText() method sets the button's label.

cb.setSelection(true);

The title is visible by default, so we select the check button by default using the setSelection() method.

cb.addListener(SWT.Selection, event -> onButtonSelect(cb));

We add a listener object to the SWT.Selection event type of the button.

private void onButtonSelect(Button cb) {

    if (cb.getSelection()) {
        shell.setText("Check button");
    } else {
        shell.setText("");
    }        
}

Inside the onButtonSelect() method, we show or hide the title of the window, depending on the state of the check button. The state of the check button is determined with the getSelection() method.

Check button
Figure: Check button

Spinner

Spinner control allows to select a number from a range of values. The value can be selected by clicking on the up and down arrows or by pressing the Arrow up and Arrow down keys, or the Page up and Page down keys.

SpinnerEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;

public class SpinnerEx {
    
    private Label label;
    
    public SpinnerEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {    
        
        Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);
        
        RowLayout layout = new RowLayout();
        layout.marginLeft = 10;
        layout.marginTop = 10;
        layout.spacing = 30;
        layout.center = true;
        shell.setLayout(layout);
        
        Spinner spinner = new Spinner(shell, SWT.BORDER);
        spinner.setMinimum(0);
        spinner.setMaximum(100);
        spinner.setSelection(0);
        spinner.setIncrement(1);
        spinner.setPageIncrement(10);       
        spinner.setLayoutData(new RowData(30, -1));
        
        spinner.addListener(SWT.Selection, event -> onSelected(spinner));
        
        label = new Label(shell, SWT.NONE);
        label.setText("0");
        
        shell.setText("Spinner");
        shell.setSize(200, 150);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }        
    }
    
    private void onSelected(Spinner spinner) {
        
        String val = spinner.getText();
        label.setText(val);
        label.pack();
    }
    
    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        SpinnerEx ex = new SpinnerEx(display);
        display.dispose();
    }    
}

The example has a Spinner and a Label. The selected value from the spinner is displayed in the label.

Spinner spinner = new Spinner(shell, SWT.BORDER);

An instance of the Spinner control is created.

spinner.setMinimum(0);
spinner.setMaximum(100);
spinner.setSelection(0);
spinner.setIncrement(1);
spinner.setPageIncrement(10);  

We use the spinner API to specify the minimum, maximum, current, increment, and page increment values.

spinner.addListener(SWT.Selection, event -> onSelected(spinner));

A listener waiting for spinner's selection events is added to the control. When the event is triggered, the onSelected() method is invoked.

private void onSelected(Spinner spinner) {
    
    String val = spinner.getText();
    label.setText(val);
    label.pack();
}

We get the current value of the spinner and set it to the label component.

Spinner
Figure: Spinner

List widget

List widget enables a user to select an option from a list of items. A list can be single-selection or multiple-selection.

ListWidgetEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program shows the List widget.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class ListWidgetEx {
    
    private Label status;

    public ListWidgetEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {

        Shell shell = new Shell(display);

        status = new Label(shell, SWT.NONE);
        status.setText("Ready");

        FormLayout layout = new FormLayout();
        layout.marginHeight = 5;
        layout.marginWidth = 5;
        layout.spacing = 5;
        shell.setLayout(layout);

        FormData labelData = new FormData();
        labelData.left = new FormAttachment(0);
        labelData.right = new FormAttachment(100);
        labelData.bottom = new FormAttachment(100);
        status.setLayoutData(labelData);

        List list = new List(shell, SWT.BORDER);

        list.add("Aliens");
        list.add("Capote");
        list.add("Neverending story");
        list.add("Starship troopers");
        list.add("Exorcist");
        list.add("Omen");

        list.addListener(SWT.Selection, event -> onListItemSelect(list));

        FormData listData = new FormData();
        listData.width = 250;
        listData.height = 200;
        listData.left = new FormAttachment(shell, 0);
        listData.top = new FormAttachment(shell, 0);
        listData.right = new FormAttachment(100, 0);
        listData.bottom = new FormAttachment(status, 0);
        list.setLayoutData(listData);

        shell.setText("List");
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    private void onListItemSelect(List list) {
        
        String[] items = list.getSelection();
        status.setText(items[0]);        
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        ListWidgetEx ex = new ListWidgetEx(display);
        display.dispose();
    }
}

In this example, the selected item from the list widget is shown in the statusbar.

status = new Label(shell, SWT.NONE);
status.setText("Ready");

A label widget is used for a statusbar. SWT does not use a native widget for a statusbar.

FormLayout layout = new FormLayout();
layout.marginHeight = 5;
layout.marginWidth = 5;
layout.spacing = 5;
shell.setLayout(layout);

We use the FormLayout widget to arrange our widgets on the window. Some margins and spacing are set.

FormData labelData = new FormData();
labelData.left = new FormAttachment(0);
labelData.right = new FormAttachment(100);
labelData.bottom = new FormAttachment(100);
status.setLayoutData(labelData);

This code attaches the status label at the bottom of the window; the usual place for a statusbar.

List list = new List(shell, SWT.BORDER);

A List widget is created. The default selection mode is single-selection.

list.add("Aliens");
list.add("Capote");
list.add("Neverending story");
list.add("Starship troopers");
list.add("Exorcist");
list.add("Omen");

It is filled with data.

list.addListener(SWT.Selection, event -> onListItemSelect(list));

We add a selection listener to the List widget. On list selection event, the onListItemSelect() method is invoked.

FormData listData = new FormData();
listData.width = 250;
listData.height = 200;
listData.left = new FormAttachment(shell, 0);
listData.top = new FormAttachment(shell, 0);
listData.right = new FormAttachment(100, 0);
listData.bottom = new FormAttachment(status, 0);
list.setLayoutData(listData);

This code makes the List widget take the bulk of the window's area. The width and height properties specify the preferred size of the list.

private void onListItemSelect(List list) {
    
    String[] items = list.getSelection();
    status.setText(items[0]);        
}

Inside the onListItemSelect(), we determine the selected item of the list and set it to the statusbar.

List widget
Figure: List widget

Slider

Slider is a widget that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a volume control.

SliderEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;


/**
 * ZetCode Java SWT tutorial
 *
 * In this program, we use the slider
 * widget to create a volume control
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class SliderEx {

    private Shell shell;
    private Label label;
    private Image mute;
    private Image min;
    private Image med;
    private Image max;


    public SliderEx(Display display) {

        initUI(display);
    }

    private void loadImages() {

        Device dev = shell.getDisplay();

        try {

            mute = new Image(dev, "mute.png");
            min = new Image(dev, "min.png");
            med = new Image(dev, "med.png");
            max = new Image(dev, "max.png");

        } catch(Exception e) {

            System.out.println("Cannot load images");
            System.out.println(e.getMessage());
            System.exit(1);
        }       
    }


    private void initUI(Display display) {

        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        loadImages();

        RowLayout layout = new RowLayout();
        layout.marginLeft = 30;
        layout.marginTop = 30;
        layout.spacing = 30;
        layout.fill = true;
        shell.setLayout(layout);

        Slider slider = new Slider(shell, SWT.HORIZONTAL);
        slider.setMaximum(100);
        slider.setLayoutData(new RowData(180, -1));

        label = new Label(shell, SWT.IMAGE_PNG);
        label.setImage(mute);

        slider.addListener(SWT.Selection, event -> onSelection(slider));
        
        shell.setText("Slider");
        shell.setSize(350, 200);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    private void onSelection(Slider slider) {
        
        int value = slider.getSelection();

        if (value == 0) {
            label.setImage(mute);
            label.pack();
        } else if (value > 0 && value <= 30) {
            label.setImage(min);
        } else if (value > 30 && value < 80) {
            label.setImage(med);
        } else {
            label.setImage(max);
        }               
    }

    @Override
    public void finalize() {

        mute.dispose();
        med.dispose();
        min.dispose();
        max.dispose();
    }

    public static void main(String[] args) {

        Display display = new Display();
        SliderEx ex = new SliderEx(display);
        ex.finalize();
        display.dispose();
    }
}

In the example above, we have a Slider and a Label widget. By dragging the knob of the slider we change the Image displayed in the label.

try {
        
    mute = new Image(dev, "mute.png");
    min = new Image(dev, "min.png");
    med = new Image(dev, "med.png");
    max = new Image(dev, "max.png");
    
} catch(Exception e) {
        
    System.out.println("Cannot load images");
    System.out.println(e.getMessage());
    System.exit(1);
} 

Images are loaded from the disk.

Slider slider = new Slider(shell, SWT.HORIZONTAL);
slider.setMaximum(100);

A Slider widget is created. Its maximum value is 100.

label = new Label(shell, SWT.IMAGE_PNG);
label.setImage(mute);

With the SWT.IMAGE_PNG parameter, the label widgets displays a PNG image. The setImage() method sets the image to the label.

slider.addListener(SWT.Selection, event -> onSelection(slider));

A listener is added to the slider widget.

int value = slider.getSelection();

Inside the onSelection() method, we obtain the value of the slider widget with the getSelection() method.

if (value == 0) {
    label.setImage(mute);
    label.pack();
} else if (value > 0 && value <= 30) {
    label.setImage(min);
} else if (value > 30 && value < 80) {
    label.setImage(med);
} else {
    label.setImage(max);
}

Depending on the obtained value, we change the picture in the label widget.

@Override
public void finalize() {

    mute.dispose();
    med.dispose();
    min.dispose();
    max.dispose();
}

At the end, the the resources are released.

Slider widget
Figure: Slider widget

Combo widget

Combo is a widget that allows the user to choose from a drop down list of options.

ComboEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * In this program, we use the Combo
 * widget to select an option. 
 * The selected option is shown in the
 * Label widget.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class ComboEx {

    private Label label;
    
    public ComboEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {

        Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        RowLayout layout = new RowLayout(SWT.VERTICAL);
        layout.marginLeft = 50;
        layout.marginTop = 30;
        layout.spacing = 30;
        shell.setLayout(layout);

        Combo combo = new Combo(shell, SWT.DROP_DOWN);
        combo.add("Ubuntu");
        combo.add("Fedora");
        combo.add("Arch");
        combo.add("Red Hat");
        combo.add("Mint");
        combo.setLayoutData(new RowData(150, -1));

        label = new Label(shell, SWT.LEFT);
        label.setText("...");   

        combo.addListener(SWT.Selection, event -> onSelected(combo));

        shell.setText("Combo");
        shell.setSize(300, 250);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    private void onSelected(Combo combo) {
        
        label.setText(combo.getText());
        label.pack();        
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        ComboEx ex = new ComboEx(display);
        display.dispose();
    }
}

The example shows a combo and a label. The combo has a list of six options. These are the names of Linux distros. The label widget shows the selected option from the combo box.

Combo combo = new Combo(shell, SWT.DROP_DOWN);

A Combo widget is created.

combo.add("Ubuntu");
combo.add("Fedora");
combo.add("Mandriva");
combo.add("Red Hat");
combo.add("Mint");

The combo widget is filled with data.

private void onSelected(Combo combo) {
    
    label.setText(combo.getText());
    label.pack();        
}

We set the selected text to the label widget. The pack() method makes the label fit the size of the new string from the combo.

Combo widget
Figure: Combo widget

In this part of the Java SWT tutorial, we described some widgets of the SWT library.