Vardan Hovhannisyan Vardan Hovhannisyan - 7 months ago 25
Java Question

How to highlight text in SWT Combo?

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

org.eclipse.swt.widgets.Combo
).

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
Answer

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 = ...
combo.setText("IP: 1.1.1.1");
String query = "IP";

setSelection(combo, query);