请教专家,如何使得JEditorPane(编辑器组件)中的指定字符串为不同的颜色(即所有字符不是同一种颜色,功能相当于文本编辑器的程序分析功能),例如JEditorPane控件中有一段字符,我要指定的某些单词为一种颜色(事先不知道单词出现的位置,字符串色输入是随意的) 
eg: 
private String a=null; 
public int []aa=new int[5];  
public void insert(){......}       
实现将这句中的关键字显示为蓝色等等之类的效果。。 
效果图如下: 
private String a=null
public int []aa=new int[5];  
public void insert(){......}  尽量回答详尽一点,麻烦你了~~!

解决方案 »

  1.   

    仔细看这段代码中的方法:
    private static void createAndShowGUI() {
            JFrame frame = new JFrame("Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(350, 400);        try {
                JTextPane textPane = new JTextPane();
                StyledDocument doc = (StyledDocument) textPane.getDocument(); /////关键之处, 取得Document.
                Style style = doc.addStyle("StyleName", null);            // Italic
                StyleConstants.setItalic(style, false);            // Bold
                StyleConstants.setBold(style, true);
                doc.insertString(doc.getLength(), "Some Text\n", style);            // Font Family
                StyleConstants.setFontFamily(style, "tahoma");            // Font Size
                StyleConstants.setFontSize(style, 30);
                doc.insertString(doc.getLength(), "Some Text\n", style);            // Background Color
                StyleConstants.setBackground(style, Color.blue);  //// 之里是设置文字的背景色.
                
                // Insert an image icon
                StyleConstants.setIcon(style, new ImageIcon("Adium.png"));            // Foreground Color
                StyleConstants.setForeground(style, Color.white); /// 这里就是设置字体的颜色.            // Append to document.
                doc.insertString(doc.getLength(), "Some Text", style);
                
                frame.getContentPane().add(textPane);
            } catch (BadLocationException e) {
            }        frame.setVisible(true);
        }