我在 JDialog 中有两个 JEditorPanes。第一个 JEditorPane 显示一个 HTML 文档,其中包含可单击的链接列表。第二个在用户单击链接时显示 URL。
我想将单击的链接的颜色更改为黑色,以便用户轻松识别他上次单击的链接。
我使用了这段代码
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (e.getSource() instanceof JEditorPane) {
JEditorPane editor = ((JEditorPane) e.getSource());
editor.requestFocusInWindow();
editor.setSelectionStart(e.getSourceElement().getStartOffset());
editor.setSelectionEnd(e.getSourceElement().getEndOffset());
editor.setSelectedTextColor(Color.black);
editor.setSelectionColor(Color.white);
loadUrl(e.getUrl);
}
}
}
遗憾的是,这仅在JEditorPane具有焦点时才起作用。由于我的 JDialog 中还有一个 JTextField,我希望永远不会失去焦点,因此我当前的解决方案不再有效。
我尝试了提供的解决方案 here ,但它们对我来说不起作用。
编辑:不幸的是,使用 CSS 不起作用。这是我的 JEditorPane 中显示的 HTML 代码
<html>
<head>
<style type="text/css">a:hover{color:red;}</style>
<title>title</title>
</head>
<body><ul><li><a href="file:/pathToFile.html">Path to File</a></li></ul>
</body>
</html>
但我仍然没有得到悬停效果。
编辑2:发布了我自己的问题解决方案作为答案。不过我很想知道为什么 CSS 不起作用。
最佳答案
您可以使用CSS能力 只需编写这段代码即可
HTML:
<a href="#" > something </a>
CSS:
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a: visited {
color: green;
}
/* mouse over link */
a:hover {
color: pink;
}
/* selected link */
a:active {
color: blue;
}
关于java - 单击后更改 HTMLPanel 中超链接的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480185/