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 に答える