java - 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
) 不为空,并且字符串总是会插入到有效位置...
原因是什么?我使用了错误的类?
解决方案
如果您尝试插入与文档末尾的文本具有相同属性的文本,则可以执行以下操作:
int pos = doc.getLength();
Element element = doc.getCharacterElement(pos - 1);
doc.insertString(pos, "more green text", element.getAttributes());
推荐阅读
- google-sheets - 带有标签而不是数字的 Google 电子表格 GeoChart
- java - 使用java中的for每个循环打印类成员,其实例存储在Class类型的LinkedList中
- python - 从终端获取输出并将其写入文件 FileNotFoundError: [Errno 2] No such file or directory error found in python
- ios - 操纵杆的额外半圆线
- apache-nifi - 如何在 Apache Druid 中将嵌套数据转换为扁平数据
- spring - 为什么在实现基本身份验证时需要身份验证提供程序?春季安全
- html - 徽标图像未推到导航的左上角
- asp.net-mvc-5 - 如何在 module-zero-template 中为 Web api 自定义 OAuthBearerAuthentication
- java - 如果 outputStream.close() 失败,流仍然会被关闭,系统资源仍然会被释放?
- python - tkinter 笔记本小部件框架限制