Vardan Hovhannisyan Vardan Hovhannisyan - 10 months ago 53
Java Question

How to highlight text in SWT Combo?

I would like to highlight a text in a combo box (


For example, suppose that the combo text is "IP:6061".
I would like to highlight "IP". How can I do that?

enter image description here

Baz Baz

Here's a reusable solution:

private void setSelection(Combo combo, String query)
    String comboText = combo.getText();

    int index = comboText.indexOf(query);

    if(index != -1)
        combo.setSelection(new Point(index, index + query.length()));

You could add an else clause to remove the selection if that's what you want to happen when there's no match in the text.

Call it like this:

Combo combo = ...
String query = "IP";

setSelection(combo, query);