我在JEditorPane
搜索了如何制作可点击链接,我发现了这个问题:
Is it possible to create programs in Java that create text to link in Chrome?
这非常有用,但我的代码使用重复语句在循环中添加链接:
JEditorPane jep = new JEditorPane();
jep.setContentType("text/html");
jep.setEditable(true);// Because replaceSelection can't work with disabled edit
for ( int i = 1; i <= 3; i++ ){
jep.replaceSelection(
"Welcome to <a href='https://stackoverflow.com/'>StackOverflow i </a>.");
}
jep.setEditable(false);
现在它只显示没有可点击链接的文字。我怎么能做对的?我真的需要replaceSelection
方法。
答案 0 :(得分:1)
在replaceSelection()
上使用HTMLDocument
插入原始字符串;您想要插入HTML锚标记。你可以,
自己管理原始HTML文本,如下所示,让setText()
处理解析。
使用现有的HTMLEditorKit
嵌套操作之一。
使用here中的一种自定义方法。
import java.awt.Desktop;
import java.awt.HeadlessException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
/**
* @see https://stackoverflow.com/a/16447176/230513
* @see https://stackoverflow.com/a/14170141/230513
*/
public class Test {
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
display();
}
});
}
private static String create(int i) {
StringBuilder sb = new StringBuilder();
sb.append("Welcome to <a href=");
sb.append("'http://www.example.com'>Example ");
sb.append(i);
sb.append("</a>.<br>");
return sb.toString();
}
private static void display() throws HeadlessException {
JEditorPane jep = new JEditorPane();
jep.setContentType("text/html");
StringBuilder sb = new StringBuilder();
sb.append("<b>Welcome</b>:<br><hr>");
for (int i = 1; i <= 3; i++) {
sb.append(create(i));
}
sb.append("<hr>");
jep.setText(sb.toString());
jep.setEditable(false);
jep.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) {
System.out.println(e.getURL());
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(e.getURL().toURI());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(jep);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}