向文档里添加带色彩的文字

来源:互联网 发布:学校机房网络一般布局 编辑:程序博客网 时间:2024/05/21 12:06
//package mybole;/** *向文档里添加带色彩的文字 *@author blue_仰望 */import java.awt.Color;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextPane;import javax.swing.text.AttributeSet;import javax.swing.text.SimpleAttributeSet;import javax.swing.text.StyleConstants;import javax.swing.text.StyleContext;public class Swt extends JTextPane{public void append(Color c, String s){StyleContext sc = StyleContext.getDefaultStyleContext();AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);int len = getDocument().getLength();setCaretPosition(len);setCharacterAttributes(aset, false);replaceSelection(s);}public static void main(String[] args){Swt pane = new Swt();for(int n=1; n<=4; n+=1){pane.append(Color.black, String.valueOf(n)+"");}JFrame f = new JFrame("ColorPane example");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setContentPane(new JScrollPane(pane));f.setSize(600,400);f.setVisible(true);}}