2010-11-17 25 views
2

當使用JTextPane方法insertIcon(),javadoc的狀態"...This is represented in the associated document as an attribute of one character of content."檢索的JTextPane的AttributeSet值

如何取回我的插入圖標的信息?我曾嘗試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()); 
     } 
    } 
} 

回答

2

使用元素的文檔來獲得屬性:

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

一旦你有根元素,你可以得到與您所選文本的元素。首先在起始偏移處找到元素,然後繼續循環遍歷每個元素,直到達到結束偏移量。

+0

嘿camickr,請你提供一些關於元素循環的更多細節。 'root.getElementCount()'總是爲我返回1。根類是'BranchElement(section)'。所以我試過'BranchElement current = null; if(root.getName()。equals(「section」)){current =(BranchElement)root;}枚舉children = current.children();'但我認爲我會朝錯誤的方向 – 2010-11-17 22:30:41

+0

使用getElement ..) 方法。如果您需要更多幫助發佈您的SSCCE。 (http://sscce.org) – camickr 2010-11-18 02:58:18

0
StyledDocument doc=(StyledDocument)textComponent.getDocument(); 
int selStart=textComponent.getSelectionStart(); 
int selEnd=textComponent.getSelectionEnd(); 

然後使用doc.getCharacterElement()方法傳遞start來獲得第一個字符elem。然後使用elem getEndOffset()你可以得到下一個char元素。檢查元素的開始和結束偏移量是否小於選擇結束。