日期:2014-05-20 浏览次数:20851 次
public static void main(String[] args) {
        JFrame frame = new JFrame("JTextPane");   
        JTextPane textPane = new JTextPane();
        
        SimpleAttributeSet attrSet = new SimpleAttributeSet(); //属性对象
        StyleConstants.setForeground(attrSet,Color.red); //属性设置颜色   ,要设置不同颜色,修改Color.red就可以
        Document doc = textPane.getDocument(); //得到JTextPane的Document 
        try {   
             doc.insertString(doc.getLength(),"今天是2012年6月15日", attrSet); //插入文字,并添加颜色属性
        }catch(BadLocationException e){   
             e.printStackTrace();  
        } 
        frame.getContentPane().add(textPane,BorderLayout.CENTER);//frame里添加进textPane
        frame.setSize(200,200);
        frame.setVisible(true);
    }
------解决方案--------------------
支持楼上,
+++
下面就是每行的颜色都不一样;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class ColorTest {
	
	public static void main(String[] args) {
       JFrame frame = new JFrame("Color"); 
       frame.setSize(300,400);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setLocationRelativeTo(null);
       JTextPane textPane = new JTextPane();
      
       SimpleAttributeSet attrSet = new SimpleAttributeSet(); //属性对象
       Document doc = textPane.getDocument(); //得到JTextPane的Document  
     
       try {  
       	 StyleConstants.setForeground(attrSet,Color.red); //属性设置颜色   ,要设置不同颜色,修改Color.red就可以
            doc.insertString(doc.getLength(),"我是红色\n", attrSet); //插入文字,并添加颜色属性
            StyleConstants.setForeground(attrSet,Color.blue);
            doc.insertString(doc.getLength(), "我是蓝色\n", attrSet);
            StyleConstants.setForeground(attrSet,Color.green);
            doc.insertString(doc.getLength(), "我是绿色\n", attrSet);
            StyleConstants.setForeground(attrSet,Color.black);
            doc.insertString(doc.getLength(), "我是黑色\n", attrSet);
       }catch(BadLocationException e){  
            e.printStackTrace(); 
       }  
       frame.add(textPane);//frame里添加进textPane
       frame.setVisible(true);
   }
}