5.2. Text ViewersTextViewer类封装了StyledText控件 (参见 Figure 5-11 TextViewer 层次图)。文本可以拥有很多不同的风格,像文字颜色,背景色,是否粗体等。文本查看器使用文字框控件,为客户程序提供了文档模型,并管理文档模型到风格化文字信息的转换。Figure 5-11. TextViewer 层次图常用API包括: 下面的例子创建了文本查看器:(参见 Figure 5-12)。 import org.eclipse.jface.text.*;
import org.eclipse.swt.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class TextViewerExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Text Viewer Example");
shell.setBounds(100, 100, 225, 125);
shell.setLayout(new FillLayout());
final TextViewer textViewer =
new TextViewer(shell, SWT.MULTI | SWT.V_SCROLL);
String string = "This is plain text\n"
+ "This is bold text\n"
+ "This is red text";
Document document = new Document(string);
textViewer.setDocument(document);
TextPresentation style = new TextPresentation();
style.addStyleRange(
new StyleRange(19, 17, null, null, SWT.BOLD));
Color red = new Color(null, 255, 0, 0);
style.addStyleRange(
new StyleRange(37, 16, red, null));
textViewer.changeTextPresentation(style, true);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
Figure 5-12. TextViewer example.创建文本查看器后,创建Document对象保存文本信息,并被赋于文本查看器。然后创建TextPresentation 对象,使其持有风格范围信息。设置了两种风格范围:一种是文字粗体,一种是文字颜色为红色。 StyleRange 构造方法的第一个参数是文本中要应用此风格的第一个字符的序列号。第二个参数是要应用此风格的字符的个数。最后,风格对象被赋于查看器。 |
5.3. 总结JFace 查看器在 Eclipse 插件开发中使用的很广泛。查看器对基础Eclipse控件提供了面向对象的封装,可以很容易的对高层次的域对象进行封装,而不是处理基本的文字,数字和图片。同样的,文本查看器可以很容易的处理需要使用复杂风格的文本。在第 7 章, 视图 将进行更详细的介绍。 参考书目: 本章源代码(www.qualityeclipse.com/projects/source-ch-04-and-05.zip). Gauthier, Laurent, "使用SWT/JFace创建并发布表格编辑器," Mirasol Op'nWorks, 2003,7,3 (www.eclipse.org/articles/Article-Table-viewer/table_viewer.html). Grindstaff, Chris, "怎样使用JFace树查看器," ,2002,5,5 (www.eclipse.org/articles/treeviewer-cg/TreeViewerArticle.htm). |
本文介绍了Eclipse中的TextViewer组件,详细讲解了其API及如何创建文本查看器实例。TextViewer能够处理复杂的文本样式需求,如粗体和颜色设置。
425

被折叠的 条评论
为什么被折叠?



