How to change the color of specific words in a JTextPane?

前端 未结 4 1230
醉酒成梦
醉酒成梦 2020-11-28 07:54

How do I change the color of specific words in a JTextPane just while the user is typing? Should I override JTextPane paintComponent m

4条回答
  •  心在旅途
    2020-11-28 08:13

    Overwriting paintComponent will not help you.

    This is not an easy one, but not impossible either. Something like this will help you:

    DefaultStyledDocument document = new DefaultStyledDocument();
    JTextPane textpane = new JTextPane(document);
    StyleContext context = new StyleContext();
    // build a style
    Style style = context.addStyle("test", null);
    // set some style properties
    StyleConstants.setForeground(style, Color.BLUE);
    // add some data to the document
    document.insertString(0, "", style);
    

    You may need to tweak this, but at least it shows you where to start.

提交回复
热议问题