Java SWT overlapping/multiple 样式范围

Java SWT overlapping/multiple StyleRanges

我在我的项目中使用了 StyledText,其中有很多文本可以根据某些事件具有不同的样式,有时这些样式可以重叠,因此可以设置代表黄色背景颜色的样式对于已经具有红色前景色 styleRange 的区域。

这是一个不代表闭源项目的代码示例:

        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);

0-9的第一种样式是红色前景色,2-9的第二种样式是黄色背景,我得到的是只有0-1会有红色前景色,而2-9 将有黑色前景色和黄色背景,而我想要的是 2-9 有红色前景和黄色背景。

结果:

我想要的样子:

我的问题是,如何设置新的 styleRange 不会删除旧样式范围或至少复制以前的特征以防万一为空?

谢谢。

JavaDoc of setStyleRange() 几乎说明了一切:

The new style overwrites existing styles for the specified range. Existing style ranges are adjusted if they partially overlap with the new style

这意味着您必须单独定义每个部分:

  • 红色文字,白色背景
  • 红色文字,黄色背景

样式范围不能重叠。您将不得不编写代码来组合它们重叠的范围以实现您想要的。

如果可以使用 JFace,TextPresentation class 可以合并重叠范围。您可以单独使用它,也可以将其与 TextViewerSourceViewer class 结合使用。