javaswtstyledtext

Java SWT overlapping/multiple StyleRanges


I'm using a StyledText in my project, in it I have lots of texts that can have different styles depending on some events, sometimes these styles can overlap, so a style that represents a yellow background color can be set for an area that already has a styleRange of a red foreground color.

Here's an example in code that's not representative of the closed source project:

        text_1 = new StyledText(composite, SWT.BORDER);
        text_1.setBounds(10, 10, 320, 21);
        text_1.setText("1234567890abcdefghij");
        text_1.setStyleRange(new StyleRange(0, 9, Display.getDefault().getSystemColor(SWT.COLOR_RED), null));
        text_1.setStyleRange(new StyleRange(2, 9, null,  Display.getDefault().getSystemColor(SWT.COLOR_YELLOW)));
        text_1.setSelection(3, 7);

The first style from 0-9 is to have a red foreground color, the second for 2-9 is to have a yellow background, what I get is that only 0-1 will have a red foreground color, while 2-9 will have black foreground color with yellow background, when what I want is 2-9 to have both a red foreground and a yellow background.

Result:

How it really looks

What I want it to look like:

How it should be

My question, how can I make it so that setting a new styleRange doesn't erase the old style range or at least copies previous characteristics in case one was null?

Thank you.


Solution

  • Style ranges can't overlap. You will have to write code to combine the ranges where they overlap to achieve what you want.

    If you can use JFace the TextPresentation class can merge overlapping ranges. You can use this on its own and in combination with the TextViewer or SourceViewer classes.