import javax.swing.text.DefaultStyledDocument; //導入方法依賴的package包/類
private void createDocument() throws Exception {
super.setUp();
doc = new DefaultStyledDocument();
MutableAttributeSet boldStyle = new SimpleAttributeSet();
StyleConstants.setBold(boldStyle, true);
MutableAttributeSet italicStyle = new SimpleAttributeSet();
StyleConstants.setItalic(italicStyle, true);
MutableAttributeSet colorStyle = new SimpleAttributeSet();
StyleConstants.setForeground(colorStyle, Color.GREEN);
Style style = doc.addStyle("myStyle", null);
StyleConstants.setBackground(style, Color.RED);
style = doc.addStyle("myStylea", null);
StyleConstants.setForeground(style, Color.GREEN);
doc.insertString(0, "bold text ", boldStyle);
doc.insertString(doc.getLength(), "italic text", italicStyle);
doc.insertString(doc.getLength(),
"green text\n more green text",
colorStyle);
doc.setLogicalStyle(doc.getLength() - 1, style);
MutableAttributeSet attrs = new SimpleAttributeSet();
Icon icon = new Icon() {
public int getIconHeight() {
return 0;
}
public int getIconWidth() {
return 0;
}
public void paintIcon(final Component c, final Graphics g,
final int x, final int y) {
}
};
StyleConstants.setIcon(attrs, icon);
attrs.addAttribute(AbstractDocument.ElementNameAttribute,
StyleConstants.IconElementName);
doc.insertString(doc.getLength(), "ppp", attrs);
iconElement = doc.getCharacterElement(doc.getLength() - 1);
attrs = new SimpleAttributeSet();
StyleConstants.setComponent(attrs, new JLabel("lab1"));
attrs.addAttribute(AbstractDocument.ElementNameAttribute,
StyleConstants.ComponentElementName);
doc.insertString(doc.getLength(), "ccc", attrs);
componentElement = doc.getCharacterElement(doc.getLength() - 1);
}