下面是显示红色文字的代码例子,其他的设置类似,是由AttributeSet设置的。
package baidu.zhidao;
import java.awt.Color;
import javax.swing.JFrame;
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.StyleConstants;
public class TextPane extends JFrame
{
JTextPane jtp = null;
DefaultStyledDocument doc = null;
SimpleAttributeSet attrset = null;
public TextPane()
{
super("JTextPane model");
doc = new DefaultStyledDocument();
jtp = new JTextPane(doc);
attrset = new SimpleAttributeSet();
StyleConstants.setForeground(attrset, Color.red);
try
{
doc.insertString(doc.getLength(), "你好,我是jink2005。\n", attrset);
}
catch (BadLocationException e)
{
}
this.getContentPane().add(new JScrollPane(jtp));
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
new TextPane();
}
}
追答![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/c995d143ad4bd113053ee7a448afa40f4afb05b0?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)