2

使用该JTextPane方法insertIcon()时,javadoc 说明"...This is represented in the associated document as an attribute of one character of content."

如何检索有关我插入的图标的信息?我试过getCharacterAttributes()只有"Fetches the character attributes in effect at the current location of the caret, or null."

是否存在一种方法来查找文本选择中的所有属性,或者在某个索引处,而不仅仅是在当前插入符号位置?

编辑
这是我拼凑起来的一些示例代码,用于获取嵌入图标的文件名。

Element root = jTextPane.getDocument().getDefaultRootElement();
BranchElement current = (BranchElement) root.getElement(0);
if (current != null)
{
    Enumeration children = current.children();
    while (children.hasMoreElements())
    {
        Element child = (Element) children.nextElement();
        if (child.getName().equals("icon"))
        {
            AttributeSet attrSet = child.getAttributes();
            ImageIcon icon = (ImageIcon) StyleConstants.getIcon(attrSet);
            System.err.println(icon.getDescription());
        }
    }
}
4

2 回答 2

2

使用 Document 的 Element 获取属性:

Element root = textComponent.getDocument().getDefaultRootElement();

拥有根元素后,您可以获得与所选文本相关的元素。首先在起始偏移处找到元素,然后继续循环遍历每个元素,直到到达结束偏移。

于 2010-11-17T18:45:09.537 回答
0
StyledDocument doc=(StyledDocument)textComponent.getDocument();
int selStart=textComponent.getSelectionStart();
int selEnd=textComponent.getSelectionEnd();

然后使用 doc.getCharacterElement() 方法传递 start 来获取第一个字符元素。然后使用 elem getEndOffset() 您可以获得下一个 char 元素。检查元素开始和结束偏移小于选择结束。

于 2010-11-20T09:45:50.470 回答