JTextPane, Document insertString, javax.swing.text.BadLocationException - PullRequest
0 голосов
/ 18 ноября 2018

У меня этот класс расширяется от 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

Я не понимаю причину, потому что объект (this) не равен нулю, и строка всегда будет вставлена ​​в правильное положение ...

В чем причина? Я использую неправильный класс?

1 Ответ

0 голосов
/ 18 ноября 2018

Если вы пытаетесь вставить текст с теми же атрибутами, что и текст в конце документа, тогда вы можете сделать что-то вроде:

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