在不使用HTML标签的情况下,将颜色不同的单词添加到JEditorPane

时间:2019-01-14 21:52:09

标签: java swing awt jtextpane jeditorpane

我需要在JEditorPane中的文本上附加不同颜色的单词,但不能使用HTML。

对于JTextPanes,有几种方法可以实现此目的(请参见下面带有自定义附加功能的示例)。但是,我的应用程序需要一个JEditorPane。

我知道SO上也有几个类似的问题(例如JEditorPane set foreground color for different words),但是大多数答案最后还是诉诸于JTextPane。

// example for JTextPane: appends text to the pane in 2 different ways
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.*;

public class MyPane extends JTextPane {

    public MyPane(){
        this.setEditable(false);
    }

// there's at least 2 ways to append colored text to a JTextPane
    public void append(Color c, String s) {
        this.setEditable(true);
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, c);

// 1st possibility: set caret to the end of the text and use replaceSelection
        int len = getDocument().getLength();
        setCaretPosition(len);
        setCharacterAttributes(aset, false);
        replaceSelection(s);
        this.setEditable(false);

// 2nd possibility: use StyledDocument.insertString()
        StyledDocument doc = this.getStyledDocument();
        try {
            doc.insertString(doc.getLength(), s, aset);
        } catch (BadLocationException ex) {
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        MyPane pane = new MyPane();
        pane.append(Color.red, "test1 ");
        pane.append(Color.blue, "test2 ");


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(200, 200));
        frame.getContentPane().add(pane);
        frame.pack();
        frame.setVisible(true);
    }
}

我可以使用JTextPane,但这将在应用程序的其他部分上付出很多额外的精力,如果有其他方法,我希望避免这种情况。任何提示都受到高度赞赏。

0 个答案:

没有答案