JTextPane,Document insertString,javax.swing.text.BadLocationException

时间:2018-11-18 03:25:52

标签: java exception jtextpane

我从JTextPane

开始
public class MyClass extends JTextPane {

      public SimpleAttributeSet getAttributeSet(JTextPane textPane) {
        SimpleAttributeSet attrSet = new SimpleAttributeSet();
        if (getBackground() != null) {
          StyleConstants.setBackground(attrSet, getBackground());
        } else {
          StyleConstants.setBackground(attrSet, textPane.getBackground());
        }
        if (getForeground() != null) {
          StyleConstants.setForeground(attrSet, getForeground());
        } else {
          StyleConstants.setForeground(attrSet, textPane.getForeground());
        }
        Font font;
        if (getFont() != null) {
          font = getFont();
        } else {
          font = textPane.getFont();
        }
        StyleConstants.setFontFamily(attrSet, font.getFamily());
        StyleConstants.setItalic(attrSet, font.isItalic());
        StyleConstants.setBold(attrSet, font.isBold());
        StyleConstants.setFontSize(attrSet, font.getSize());
        return attrSet;
      }

....
....

}

运行代码,例如:

Document doc = this.getStyledDocument();
try {
  doc.insertString(doc.getLength(), "Some not null String", this.getAttributeSet(this));
} catch (BadLocationException ex) {
  Logger.getLogger("BadLocationException:" + ex.getMessage());
}

有时候我得到了:

javax.swing.text.BadLocationException

我不明白原因,因为Object(this)不为null,并且String总是会插入到有效位置...

这是什么原因? 我使用了错误的课程?

1 个答案:

答案 0 :(得分:0)

如果您要插入与文档末尾具有相同属性的文本,则可以执行以下操作:

int pos = doc.getLength();
Element element = doc.getCharacterElement(pos - 1);
doc.insertString(pos, "more green text", element.getAttributes());