5.2. Text ViewersThe TextViewer class wraps the StyledText widget (see Figure 5-11 for the TextViewer hierarchy). Individual runs of text may have different styles associated with them, including foreground color, background color, and bold. Text viewers provide a document model to the client and manage the conversion of the document to the styled text information used by the text widget. Figure 5-11. TextViewer hierarchy.
Useful APIs include:
The following example creates a text viewer containing styled text (see 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.
After creating the text viewer, a Document object is created that holds a string of text and is then assigned to the viewer. Next, a TextPresentation object is created to hold the style ranges. Two style ranges are added: one that sets a range of text to bold and a second that sets a range of text to the color red. The first argument to the StyleRange constructor is the index of the first character in the string to which the style should apply. The second argument is the number of characters that should be affected by the style. Finally, the style object is assigned to the viewer. |