JEditorPane set foreground color for different words

前端 未结 1 853
故里飘歌
故里飘歌 2020-12-04 04:13

I am currently working on a text editor, and I have this code which make the background of the specific word different from the others, but I want the foreground to edit col

相关标签:
1条回答
  • 2020-12-04 05:00

    You need to take advantage of the editors StyledDocuemnt, for a simple example...

    import java.awt.Color;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Element;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    
    public class Srap {
    
        public static void main(String[] args) {
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
    
            Style style = textPane.addStyle("I'm a Style", null);
            StyleConstants.setForeground(style, Color.red);
    
            try {
                doc.insertString(doc.getLength(), "BLAH ", style);
            } catch (BadLocationException ex) {
            }
    
            StyleConstants.setForeground(style, Color.blue);
    
            try {
                doc.insertString(doc.getLength(), "BLEH", style);
            } catch (BadLocationException e) {
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题