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 开发者_C百科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.
Edit:
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 );
}
try this:
doc.setCharacterAttributes(0, doc.getLength() + 1, attributeSet, false);
精彩评论