tags:

views:

43

answers:

2

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.

+3  A: 

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 );
}
Ash
+1  A: 

try this:

    doc.setCharacterAttributes(0, doc.getLength() + 1, attributeSet, false);
objects
This would change the style of the whole document, which is not what I want. I only want to change the style of the character about to be typed.
EA