首页 > 解决方案 > JTextPane、文档 insertString 、 javax.swing.text.BadLocationException

问题描述

我有这个类从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) 不为空,并且字符串总是会插入到有效位置...

原因是什么?我使用了错误的类?

标签: javaexceptionjtextpane

解决方案


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

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

推荐阅读