Ali
Ali

Reputation: 267077

Changing color of certain words in a SWT Label?

In Swing, its possible to use HTML to style the words on a label. E.g if I wanted a certain word on a label to be bolded or be of a different color, I could do that with HTML.

Is there an equivalent feature for SWT? Say if I had the words "A quick brown fox jumped over a lazy dog" as the text of a label, and I wanted to change the color of "fox" to be brown, how would I do that?

Upvotes: 2

Views: 5127

Answers (1)

Baz
Baz

Reputation: 36894

If you really need a Label, you can use the code below. Otherwise I would suggest a StyledText (as mentioned in the comments):

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    Label label = new Label(shell, SWT.NONE);
    label.setText("Blue and not blue");

    Color blue = display.getSystemColor(SWT.COLOR_BLUE);

    final TextLayout layout = new TextLayout(display);
    layout.setText("Blue and not blue");
    final TextStyle style = new TextStyle(display.getSystemFont(), blue, null);

    label.addListener(SWT.Paint, new Listener() {
        @Override
        public void handleEvent(Event event) {
            layout.setStyle(style, 0, 3);
            layout.draw(event.gc, event.x, event.y);
        }
    });

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

}

With StyledText it would look something like this:

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    StyledText text = new StyledText(shell, SWT.NONE);
    text.setEditable(false);
    text.setEnabled(false);
    text.setText("Blue and not blue");

    Color blue = display.getSystemColor(SWT.COLOR_BLUE);

    StyleRange range = new StyleRange(0, 4, blue, null);

    text.setStyleRange(range);

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

Upvotes: 7

Related Questions