简体   繁体   English

如何设置要在JTextPane中键入的文本的样式

[英]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. 我有一个JTextPane,并且能够修改其中一部分文本的样式。

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. 假设没有选择JTextPane中的任何内容,我希望能够修改尚未包含在其中的部分的样式,也就是说,设置用户接下来要键入的样式。

Using setCharacterAttributes(start, length, style, attributeSet, replace) with length = 0 does not seem to do it. 使用setCharacterAttributes(start,length,style,attributeSet,replace)设置length = 0似乎不行。

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. 如果在文本窗格的文档上设置了DocumentFilter (假设您正在使用具有setDocumentFilter方法的AbstractDocument子类),则可以在插入或替换文本时向文本添加属性集。

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': 作为一个简单的例子,这是DocumentFilterreplace方法的一种实现,当用户键入“ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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