这是我的问题:
我正在尝试使用以下代码行添加指向我的 JEditorPane 的链接:
gui.textfield.getDocument().insertString(gui.textfield.getDocument().getLength(), guiModel.getResponseString(serverResponse), null);
和
public String getResponseString(String serverResponse){
return currentDate()+" "+serverResponse.replaceAll("http://.+?(com|net|org|de)/{0,1}", "<a href=\"$0\">$0</a>")+"\n";
}
请注意,gui.textfield 是我的 JEditorPane。
但是,我可以看到它正在工作,但整个标签只是落在字符串中,并且没有被检测为链接。
我的 JEditorPane 有以下调整:
textfield = new JEditorPane ();
textfield.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
textfield.setEditable(false);
我做错了什么?
最佳答案
事实上,您只是插入字符串而不是更改 HTMLDocument 的结构。
添加链接的最简单方法是创建人工 Eleemnt 并替换其外部 html。
SimpleAttributeSet a=new SimpleAttributeSet();
a.addAttribute("DUMMY_ATTRIBUTE_NAME","DUMMY_ATTRIBUTE_VALUE");
doc.setCharacterAttributes(start, text.length(), a, false);
Element elem=doc.getCharacterElement(start);
String html="<a href='"+text+"'>"+text+"</a>";
doc.setOuterHTML(elem, html);
在此处查看链接自动创建的工作示例 http://java-sl.com/tip_autocreate_links.html
关于java - JEditorPane 未检测到 <a> 标签,而是将它们放入我的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30438742/