/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
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[]) {
String title = (args.length == 0 ? "TextPane Example" : args[0]);
JFrame frame = new JFrame(title);
Container content = frame.getContentPane();
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);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
// Third style for icon/component
Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
Icon icon = new ImageIcon("Computer.gif");
JLabel label = new JLabel(icon);
StyleConstants.setComponent(labelStyle, label);
// Insert content
try {
document.insertString(document.getLength(), "Ignored", labelStyle);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
content.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
|