首页 > 解决方案 > 单击后更改 HTMLPanel 中超链接的颜色

问题描述

我在 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,我希望永远不会失去焦点,因此我当前的解决方案不再有效。

我尝试了这里提供的解决方案,但在我的情况下它们不起作用。

编辑:不幸的是,使用 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 不起作用。

标签: javahtmlswingjeditorpane

解决方案


可以使用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;

}

推荐阅读