`
java-mans
  • 浏览: 11456341 次
文章分类
社区版块
存档分类
最新评论

JTextPane加入不同属性的文本

 
阅读更多

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();
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics