日期:2014-05-20  浏览次数:20590 次

求一段关于foreground的代码
我想在JTextArea上打印不同颜色的字,而setForeground设置一个容器内字符串的整体颜色。求一段代码,要求
1.在JTextArea或者其他能打印字符串的容器中打印出不同颜色的字
2.代码不要太过于复杂,要求有关键部分的注释注释
谢谢啦

------解决方案--------------------
Java code
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);
}

}