---
title: "JTextPane加入不同属性的文本"
author: "holoblog"
date: "2011-11-06T14:13:00Z"
tags: []
slug: "jtextpane"
draft: false
lastmod: "2011-11-20T20:23:43Z"
id: 1268859
url: "https://holoblog.iteye.com/blog/1268859"
---

package 文本域;

import javax.swing.\*;  
import java.awt.\*;  
import java.awt.event.\*;  
import javax.swing.text.\*;  
import java.io.\*;

public class Test {  
JFrame myFrame;  
JTextPane myTextPane;

public Test() {

myFrame = new JFrame("JTextPane");  
myTextPane = new JTextPane();

}

/\**  
\* 插入文字  
\*  
\* @param str  
\* 字符串  
\* @param attrSet  
\* 字符串详细描述  
\*/  
public void insert(String str, AttributeSet attrSet) {  
Document doc = myTextPane.getDocument();  
str = "\\n" + str;

try {  
doc.insertString(doc.getLength(), str, attrSet);  
} catch (BadLocationException e) {  
System.out.println("BadLocationException: " + e);  
}

}

/\**  
\* 简单的设置文字使用的样式  
\*  
\* @param str  
\* 字符串  
\* @param col  
\* 颜色  
\* @param bold  
\* 是否粗体，true为粗  
\* @param fontSize  
\* 字体大小  
\*/  
public void setDocs(String str, Color col, boolean bold, int fontSize) {  
SimpleAttributeSet attrSet = new SimpleAttributeSet();  
StyleConstants.setForeground(attrSet, col);

// 颜色  
if (bold == true) {  
StyleConstants.setBold(attrSet, true);  
}// 字体类型  
StyleConstants.setFontSize(attrSet, fontSize);  
// 字体大小  
insert(str, attrSet);  
}

public void init() {  
setDocs("我爱你！", Color.BLACK, false, 20);  
setDocs("你爱我！", Color.BLUE, true, 35);  
setDocs("死心ta地", Color.red, false, 28);  
myFrame.add(myTextPane, BorderLayout.CENTER);

myFrame.addWindowListener(new WindowAdapter() {  
public void windowClosing(WindowEvent e) {  
System.exit(0);  
}  
});

myFrame.setSize(250, 360);  
myFrame.setVisible(true);  
}

public static void main(String\[] args) {  
Test test = new Test();  
test.init();  
}  
}