JEdi​​torPane未检测到<a> tags, puts them into my string instead

时间:2015-05-25 12:47:10

标签: java html swing jeditorpane

Here is my problem:

I'm trying to add links to my JEditorPane with these lines of code:

gui.textfield.getDocument().insertString(gui.textfield.getDocument().getLength(), guiModel.getResponseString(serverResponse), null);

and

public String getResponseString(String serverResponse){ 
    return currentDate()+" "+serverResponse.replaceAll("http://.+?(com|net|org|de)/{0,1}", "<a href=\"$0\">$0</a>")+"\n";       
}

Note that gui.textfield is my JEditorPane.

However, I can see it's working, but the whole Tag just lands in the string, and is not being detected as a link.

My JEditorPane has these adjustments:

    textfield = new JEditorPane ();
    textfield.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
    textfield.setEditable(false);

What am I doing wrong?

2 个答案:

答案 0 :(得分:1)

实际上,您只需插入字符串而不是更改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

答案 1 :(得分:0)

尝试使用setText方法在编辑器中设置文本。如果您希望链接作为链接工作(打开浏览器),则需要添加一个监听器。听到这个回答:Open a link in browser with java button? 此外,您可以简单地添加链接的文本,如果它是正常的HTML。如果不是你想要的答案,可能我不明白这个问题。因为我的英语不太好。