简体   繁体   中英

How to set style of the text about to be typed in a JTextPane

I have a JTextPane and I am able to modify the style of a portion of text within it.

Assuming that nothing in the JTextPane is selected, I would like to be able to modify the style of a portion that is not yet in it, that is to say, to set the style that the user is going to type next.

Using setCharacterAttributes(start, length, style, attributeSet, replace) with length = 0 does not seem to do it.

If you set a DocumentFilter on the text pane's document (assuming you're using an AbstractDocument subclass, which has the setDocumentFilter method), you can add attribute sets to the text when it is inserted or replaced.

As a quick example, this is an implementation of the replace method in a DocumentFilter that turns the text red when the user types an 'a':

public void replace( FilterBypass fb, int offset, int length,
    String text, AttributeSet attrs ) throws BadLocationException
{
  if ( text.startsWith( "a" ) )
  {
    SimpleAttributeSet newAttrs = new SimpleAttributeSet();
    StyleConstants.setForeground( newAttrs, Color.RED );
    attrs = newAttrs;
  }

  super.replace( fb, offset, length, text, attrs );
}

尝试这个:

    doc.setCharacterAttributes(0, doc.getLength() + 1, attributeSet, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM