技术开发 频道

了解TabFolder、Canvas和其他多种控件

  SWT 通过 Text 控件支持纯文本的输入和显示。对于更高级的文本表示形式,需要定义字体和颜色,因此可以使用 custom 包中的 StyledText 控件。StyledText 是可由许多 Eclipse 编辑器使用的控件。请考虑一下图 5 中所示的样式文本的示例。该文本包含不同的颜色和字体修饰,比如下划线、删除线、粗体和斜体。注意,删除线和下划线只在 Eclipse V3.1 上受到支持。

  图 5. StyledText 的例子

  必须将 StyledText 定义为以下两种相互排斥的样式之一:

  MULTI —— 显示多个行。

  SINGLE —— 显示单个行。

  StyledText 支持其他一些可选样式:

  WRAP —— 从控件的右边换行。

  READ_ONLY —— 不允许键入输入值。

  清单 11 显示了用于创建 StyledText 的代码。清单 12 使用简单的类似 XML 的语言展示了它的用法,以定义具有这些属性的文本的范围。

  清单 11. 用于创建 StyledText 的方法

1 protected StyledText createStyledText(Composite parent, int style) {
2     return new StyledText(parent, style);
3 }
4

 

  清单 12. StyledText 的例子

1 styledText = createStyledText(body, SWT.MULTI | SWT.WRAP |
2                                     SWT.FULL_SELECTION);
3 styledText.addMouseListener(new MouseAdapter() {
4     public void mouseDown(MouseEvent e) {
5         if (e.button == 3) {
6             processPopup();
7         }
8     }});
9 TextContent tc = new TextContent(body.getDisplay());
10 tc.setContent(dummyContent);
11 styledText.setText(tc.toPlainText());
12 styledText.setStyleRanges(tc.getStyleRanges());
13 :
14 protected static final String dummyContent =
15 "Just plain text!\n" +
16 "Now is the time for <b>all</b> good men " +
17 "to come to the aid of their country\n" +
18 "<red><i>To <b>be</b></i> or <i>not to <b>be</b></i>?</red> " +
19 "<blue><u>That</u> is the <so>question</so></blue>\n" +
20 "That's all folks!\n";
21

 

  StyledText 的例子使用了一个 helper 类 TextContent,以确定具有特殊属性的文本的范围。这个类包含在示例代码中,支持对文档进行分析并获得其纯文本内容,以及查找各种范围,其中的纯文本内容具有不同属性或属性组合。它创建了表示这些范围的 SWT 类 StyleRange 的一个数组。StyleRange 有一些字段,这些字段描述了这样的范围,该范围包括前景色和背景色,以及要应用的起始偏移量、长度和属性,比如字体样式(粗体或斜体)、删除线和下划线。

  StyledText 所具有的功能比这里展示的还要多。例如,在将文本输入到文档中时,文本没有任何属性,即使是在具有属性的点输入它也是如此。您可以使用 StyledText 的特性来改正这一行为。

0
相关文章