Skip to content

Combo Examples

Instances of this class are controls that allow the user to choose an item from a list of items, or optionally enter a new value by typing it into an editable text field.

Column Layout Form Snippet

Combo  Column Layout Form Snippet

A five-column ColumnLayout form of label-over-field cells, one of them a DROP_DOWN Combo, with a

hidden cell at the end of each of the first four columns. ColumnLayout stacks cells by height, so

the rows only line up across the form while the Combo cell is about as tall as a Text cell; a

taller Combo pushes the hidden cell to the top of the next column and every later column starts

one row lower.

ComboColumnLayoutFormSnippet.java
package dev.equo;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.forms.widgets.ColumnLayout;

/**
 * A five-column ColumnLayout form of label-over-field cells, one of them a DROP_DOWN Combo, with a
 * hidden cell at the end of each of the first four columns. ColumnLayout stacks cells by height, so
 * the rows only line up across the form while the Combo cell is about as tall as a Text cell; a
 * taller Combo pushes the hidden cell to the top of the next column and every later column starts
 * one row lower.
 */
public class ComboColumnLayoutFormSnippet {

    static final int CELLS = 23;
    static final int ROWS = 5;
    static final int COMBO_CELL = 3;

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("ColumnLayout form with a Combo");
        shell.setLayout(new FillLayout());

        Composite form = new Composite(shell, SWT.BORDER);
        ColumnLayout layout = new ColumnLayout();
        layout.minNumColumns = 5;
        layout.maxNumColumns = 5;
        form.setLayout(layout);

        for (int i = 0; i < CELLS; i++) {
            Composite cell = new Composite(form, SWT.NONE);
            cell.setLayout(new GridLayout(1, false));
            new Label(cell, SWT.LEFT).setText("Field " + (i + 1));
            Control field;
            if (i == COMBO_CELL) {
                Combo combo = new Combo(cell, SWT.BORDER | SWT.DROP_DOWN);
                combo.setItems("", "One", "Two");
                field = combo;
            } else {
                field = new Text(cell, SWT.BORDER);
            }
            field.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
            boolean hidden = i % ROWS == ROWS - 1;
            cell.setVisible(!hidden);
        }

        shell.setSize(1100, 420);
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }
}

View on GitHub

Keyboard Snippet

Combo  Keyboard Snippet

Drives a READ_ONLY and an editable Combo from the keyboard, reached with Tab. Up/Down/Home/End/PgDn

move the selection and fire Selection, a letter selects the next item starting with it (READ_ONLY),

Alt+Down and F4 open the list, and Enter fires DefaultSelection. After every step the Combo's

selection index, text and list visibility are printed. Every event is printed with a [repro] prefix.

Run with {@code --drive} to send the keys with java.awt.Robot. For the native baseline, call

Config.defaultToEclipse() in place of the useEquo lines and run it with runEmbedExample.

ComboKeyboardSnippet.java
package dev.equo;

import dev.equo.swt.Config;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;

import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;

/**
 * Drives a READ_ONLY and an editable Combo from the keyboard, reached with Tab. Up/Down/Home/End/PgDn
 * move the selection and fire Selection, a letter selects the next item starting with it (READ_ONLY),
 * Alt+Down and F4 open the list, and Enter fires DefaultSelection. After every step the Combo's
 * selection index, text and list visibility are printed. Every event is printed with a [repro] prefix.
 * Run with {@code --drive} to send the keys with java.awt.Robot. For the native baseline, call
 * Config.defaultToEclipse() in place of the useEquo lines and run it with runEmbedExample.
 */
public class ComboKeyboardSnippet {
    static final String[] ITEMS = {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel"};

    public static void main(String[] args) throws Exception {
        Config.useEquo(Combo.class);
        Config.useEquo(Text.class);

        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("ComboKeyboardSnippet");
        shell.setLayout(new RowLayout(SWT.VERTICAL));

        Text start = new Text(shell, SWT.BORDER);
        start.setText("start");
        Combo readOnly = combo(shell, SWT.READ_ONLY, "READ_ONLY");
        Combo editable = combo(shell, SWT.DROP_DOWN, "editable");
        display.addFilter(SWT.KeyDown, e -> log("KeyDown keyCode=" + e.keyCode + " stateMask=" + e.stateMask + " on " + e.widget));

        shell.setSize(300, 220);
        shell.open();
        start.setFocus();
        if (Arrays.asList(args).contains("--drive")) drive(display, shell, start, readOnly, editable);
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
        System.exit(0);
    }

    static Combo combo(Shell shell, int style, String name) {
        Combo combo = new Combo(shell, style);
        combo.setItems(ITEMS);
        combo.select(0);
        combo.addListener(SWT.Selection, e -> log(name + " Selection index=" + combo.getSelectionIndex()));
        combo.addListener(SWT.DefaultSelection, e -> log(name + " DefaultSelection"));
        combo.addListener(SWT.Modify, e -> log(name + " Modify text=" + combo.getText()));
        combo.addListener(SWT.FocusIn, e -> log(name + " FocusIn"));
        return combo;
    }

    static void drive(Display display, Shell shell, Control first, Combo readOnly, Combo editable) {
        Thread t = new Thread(() -> {
            try {
                Robot r = new Robot();
                r.delay(6000);
                activate(r, display, shell, first);
                display.syncExec(() -> log("focus control: " + display.getFocusControl()));
                for (boolean byClick : new boolean[] {false, true}) {
                    log("=== focus " + (byClick ? "by click" : "by Tab"));
                    if (byClick) {
                        click(r, display, readOnly);
                        step(r, display, readOnly, "Escape (close the list the click opened)", KeyEvent.VK_ESCAPE);
                        display.syncExec(() -> readOnly.select(0));
                    } else {
                        step(r, display, readOnly, "Tab", KeyEvent.VK_TAB);
                    }
                    step(r, display, readOnly, "Down", KeyEvent.VK_DOWN);
                    step(r, display, readOnly, "Down", KeyEvent.VK_DOWN);
                    step(r, display, readOnly, "Up", KeyEvent.VK_UP);
                    step(r, display, readOnly, "End", KeyEvent.VK_END);
                    step(r, display, readOnly, "Home", KeyEvent.VK_HOME);
                    step(r, display, readOnly, "PgDn", KeyEvent.VK_PAGE_DOWN);
                    step(r, display, readOnly, "d (type-ahead)", KeyEvent.VK_D);
                    step(r, display, readOnly, "Alt+Down", KeyEvent.VK_ALT, KeyEvent.VK_DOWN);
                    step(r, display, readOnly, "Escape", KeyEvent.VK_ESCAPE);
                    step(r, display, readOnly, "F4", KeyEvent.VK_F4);
                    step(r, display, readOnly, "Escape", KeyEvent.VK_ESCAPE);
                    step(r, display, readOnly, "Enter", KeyEvent.VK_ENTER);
                    if (byClick) {
                        display.syncExec(() -> editable.select(0));
                        click(r, display, editable);
                    } else {
                        step(r, display, editable, "Tab", KeyEvent.VK_TAB);
                    }
                    step(r, display, editable, "Down", KeyEvent.VK_DOWN);
                    step(r, display, editable, "Down", KeyEvent.VK_DOWN);
                    step(r, display, editable, "Alt+Down", KeyEvent.VK_ALT, KeyEvent.VK_DOWN);
                    step(r, display, editable, "Escape", KeyEvent.VK_ESCAPE);
                    step(r, display, editable, "Enter", KeyEvent.VK_ENTER);
                    if (!byClick) click(r, display, first);
                }
                log("done");
                display.asyncExec(shell::dispose);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        t.setDaemon(true);
        t.start();
    }

    static void step(Robot r, Display display, Combo combo, String label, int... keys) {
        log("--- " + label);
        for (int k : keys) r.keyPress(k);
        for (int i = keys.length - 1; i >= 0; i--) r.keyRelease(keys[i]);
        r.delay(1200);
        display.syncExec(() -> log("  state index=" + combo.getSelectionIndex() + " text=" + combo.getText()
                + " listVisible=" + combo.getListVisible() + " focus=" + display.getFocusControl()));
    }

    static void activate(Robot r, Display display, Shell shell, Control control) {
        display.syncExec(shell::forceActive);
        r.delay(500);
        Point[] center = new Point[1];
        display.syncExec(() -> {
            if (display.getFocusControl() == null) {
                Point size = control.getSize();
                center[0] = display.map(control, null, size.x / 2, size.y / 2);
            }
        });
        if (center[0] != null) {
            r.mouseMove(center[0].x, center[0].y);
            r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            r.delay(800);
        }
    }

    static void click(Robot r, Display display, Control control) {
        Point[] center = new Point[1];
        display.syncExec(() -> {
            Point size = control.getSize();
            center[0] = display.map(control, null, size.x / 2, size.y / 2);
        });
        r.mouseMove(center[0].x, center[0].y);
        r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        r.delay(1200);
    }

    static void log(String s) {
        System.out.println("[repro] " + s);
    }
}

View on GitHub

Read Only Snippet

Combo  Read Only Snippet

Demonstrates READ_ONLY combo widget.

This combo allows selection from a predefined list but doesn't allow typing.

ComboReadOnlySnippet.java
package dev.equo;

import static org.eclipse.swt.events.SelectionListener.*;

import dev.equo.swt.Config;
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

/**
 * Demonstrates READ_ONLY combo widget.
 * This combo allows selection from a predefined list but doesn't allow typing.
 */

public class ComboReadOnlySnippet {
    public static void main(String[] args) {
        Config.useEquo(Group.class);

        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setSize(300, 300);
        shell.setText("ComboReadOnlySnippet - Selection Test");
        shell.setLayout(new GridLayout(1, false));

        // READ_ONLY Combo
        Group group1 = new Group(shell, SWT.NONE);
        group1.setText("READ_ONLY Combo");
        group1.setLayout(new GridLayout(2, false));
        GridData groupData = new GridData(SWT.FILL, SWT.FILL, true, true);
        group1.setLayoutData(groupData);

        Label label1 = new Label(group1, SWT.NONE);
        label1.setText("READ_ONLY:");

        Combo readOnlyCombo = new Combo(group1, SWT.READ_ONLY);
        readOnlyCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        for (int i = 0; i < 5; i++) {
            readOnlyCombo.add("Item " + i);
        }
        readOnlyCombo.select(0);
        readOnlyCombo.addSelectionListener(widgetSelectedAdapter(e ->
                System.out.println("READ_ONLY Selection: " + readOnlyCombo.getText())));

        shell.open();

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

View on GitHub

Selection After Tab Snippet

Combo  Selection After Tab Snippet

Tabbing into an editable Combo selects all of its text, and getSelection() reports that range; typing a

character then replaces the text and leaves the caret after it. The snippet prints getText(), getSelection()

and getCaretPosition() of an editable Combo and of a Text, both preset to "Initial", after a Tab into each and

after typing "x". On Windows the Combo reports (0,7) after the Tab and (1,1) after "x"; the Text keeps the

caret at the start, so "x" is inserted before its text.

Every line is printed with a [repro] prefix. Run with {@code --drive} to send the click and keys with

java.awt.Robot. For the native baseline, drop the Config lines and run it against the stock SWT jar.

ComboSelectionAfterTabSnippet.java
package dev.equo;

import dev.equo.swt.Config;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;

import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;

/**
 * Tabbing into an editable Combo selects all of its text, and getSelection() reports that range; typing a
 * character then replaces the text and leaves the caret after it. The snippet prints getText(), getSelection()
 * and getCaretPosition() of an editable Combo and of a Text, both preset to "Initial", after a Tab into each and
 * after typing "x". On Windows the Combo reports (0,7) after the Tab and (1,1) after "x"; the Text keeps the
 * caret at the start, so "x" is inserted before its text.
 * Every line is printed with a [repro] prefix. Run with {@code --drive} to send the click and keys with
 * java.awt.Robot. For the native baseline, drop the Config lines and run it against the stock SWT jar.
 */
public class ComboSelectionAfterTabSnippet {
    public static void main(String[] args) {
        Config.useEquo(Combo.class);
        Config.useEquo(Text.class);

        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("ComboSelectionAfterTabSnippet");
        shell.setLayout(new RowLayout(SWT.VERTICAL));

        Text start = new Text(shell, SWT.BORDER);
        start.setText("start");
        Combo combo = new Combo(shell, SWT.DROP_DOWN | SWT.BORDER);
        combo.setItems("Initial", "Other");
        combo.setText("Initial");
        Text text = new Text(shell, SWT.SINGLE | SWT.BORDER);
        text.setText("Initial");
        Label values = new Label(shell, SWT.NONE);
        values.setText("\n\n\n\n");

        shell.setSize(460, 300);
        shell.open();
        String capture = Arrays.stream(args).filter(a -> a.startsWith("--capture=")).map(a -> a.substring(10))
                .findFirst().orElse(null);
        if (Arrays.asList(args).contains("--drive")) drive(display, shell, start, combo, text, values, capture);
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
        System.exit(0);
    }

    static void drive(Display display, Shell shell, Text start, Combo combo, Text text, Label values, String capture) {
        Thread t = new Thread(() -> {
            try {
                Robot r = new Robot();
                r.delay(6000);
                display.syncExec(shell::forceActive);
                r.delay(500);
                click(r, display, start);
                boolean[] active = new boolean[1];
                display.syncExec(() -> {
                    active[0] = display.getActiveShell() == shell;
                    log("shell " + shell.getBounds() + " active=" + active[0] + " focus after click: "
                            + name(display.getFocusControl(), start, text));
                });
                if (!active[0]) capture(r, display, shell, capture, "-inactive");
                key(r, KeyEvent.VK_TAB);
                boolean[] reached = new boolean[1];
                display.syncExec(() -> reached[0] = display.getFocusControl() == combo);
                if (!reached[0]) {
                    log("the Tab did not reach the window, so the keys would go elsewhere: stopping");
                    display.asyncExec(shell::dispose);
                    return;
                }
                show(display, values, "Combo after Tab: " + syncState(display, start, combo, text));
                capture(r, display, shell, capture, "-tab");
                key(r, KeyEvent.VK_X);
                show(display, values, "Combo after x: " + syncState(display, start, combo, text));
                key(r, KeyEvent.VK_TAB);
                show(display, values, "Text after Tab: " + syncState(display, start, text, text));
                key(r, KeyEvent.VK_X);
                show(display, values, "Text after x: " + syncState(display, start, text, text));
                capture(r, display, shell, capture, "");
                log("done");
                display.asyncExec(shell::dispose);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        t.setDaemon(true);
        t.start();
    }

    static String syncState(Display display, Text start, Control control, Text text) {
        String[] state = new String[1];
        display.syncExec(() -> state[0] = state(display, start, control, text));
        return state[0];
    }

    /** Prints a line and shows it in the window, so a capture of the window carries the values. */
    static void show(Display display, Label values, String line) {
        log(line);
        display.syncExec(() -> {
            String shown = values.getText().strip();
            values.setText(shown.isEmpty() ? line : shown + "\n" + line);
            values.getParent().layout(true, true);
        });
    }

    /** Saves the window as {@code <prefix><suffix>.png} when {@code --capture=<prefix>} was given. */
    static void capture(Robot r, Display display, Shell shell, String prefix, String suffix) throws java.io.IOException {
        if (prefix == null) return;
        r.delay(500);
        org.eclipse.swt.graphics.Rectangle[] bounds = new org.eclipse.swt.graphics.Rectangle[1];
        display.syncExec(() -> bounds[0] = shell.getBounds());
        java.awt.image.BufferedImage image = r.createScreenCapture(
                new java.awt.Rectangle(bounds[0].x, bounds[0].y, bounds[0].width, bounds[0].height));
        javax.imageio.ImageIO.write(image, "png", new java.io.File(prefix + suffix + ".png"));
    }

    static String state(Display display, Text start, Control control, Text text) {
        String focus = name(display.getFocusControl(), start, text);
        if (control instanceof Combo c) {
            return "focus=" + focus + " text=" + c.getText() + " selection=" + c.getSelection()
                    + " caret=" + c.getCaretPosition();
        }
        Text t = (Text) control;
        return "focus=" + focus + " text=" + t.getText() + " selection=" + t.getSelection()
                + " caret=" + t.getCaretPosition();
    }

    static String name(Control focus, Text start, Text text) {
        if (focus == null) return "none";
        if (focus == start) return "start";
        if (focus instanceof Combo) return "Combo";
        if (focus == text) return "Text";
        return focus.toString();
    }

    static void key(Robot r, int key) {
        r.keyPress(key);
        r.keyRelease(key);
        r.delay(1200);
    }

    static void click(Robot r, Display display, Control control) {
        Point[] center = new Point[1];
        display.syncExec(() -> {
            Point size = control.getSize();
            center[0] = display.map(control, null, size.x / 2, size.y / 2);
        });
        log("click at " + center[0]);
        r.mouseMove(center[0].x, center[0].y);
        r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        r.delay(1200);
    }

    static void log(String s) {
        System.out.println("[repro] " + s);
    }
}

View on GitHub