Java Reference
In-Depth Information
Loading a JTextPane with Content
Listing 15-17 provides an example that loads the content for a StyledDocument for a JTextPane .
This is just to give you an idea of the possibilities. The details of using Style , SimpleAttributeSet ,
and StyleConstants will be discussed in Chapter 16.
Listing 15-17. JTextPane Example
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
public class TextPaneSample {
private static String message =
"In the beginning, there was COBOL, then there was FORTRAN, " +
"then there was BASIC, ... and now there is Java.\n";
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("TextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);
Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
// Insert content
try {
document.insertString(document.getLength(), message, style);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
SimpleAttributeSet attributes = new SimpleAttributeSet();
StyleConstants.setBold(attributes, true);
StyleConstants.setItalic(attributes, true);
// Insert content
try {
document.insertString(document.getLength(), "Hello Java", attributes);
Search WWH ::




Custom Search