我正在尝试使用超链接实现JEditorPane。我正在使用HyperLinkListener,但它似乎永远不会触发。
代码:
JEditorPane editorPane = new JEditorPane("text/html", programInfo);
editorPane.addHyperlinkListener(e -> {
System.out.println("CLICK");
if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED))
try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
});
JOptionPane.showMessageDialog(contentPane, editorPane);
示例HTML:
<body>
<p><b>Author:</b> James - <a href="http://www.sample.co.uk">sample</a></p>
</body>
这导致了这个:
但是当我点击链接时没有任何反应。
其他信息:
我在Ubuntu 14.04上测试了这个。 我已将Look and Feel设置为系统。
答案 0 :(得分:1)
editorPane.setEditable(false);
您可以在下面找到一个自包含的示例:
public class TestFrame extends JFrame {
public static void main(String[] args) {
JEditorPane editorPane = new JEditorPane("text/html", "test <a href=\"http://example.com\">link to example.com</a>");
editorPane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
System.out.println("CLICK");
if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED)) try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
}
catch (IOException e1) {
e1.printStackTrace();
}
catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
editorPane.setEditable(false); // otherwise ignores hyperlink events!
JFrame frame = new JFrame("EditorPane Example");
frame.add(editorPane);
frame.setSize(300,200);
frame.setVisible(true);
} }
(抱歉,我删除了lambda因为我没有在这台电脑上安装jdk8)