0

I have two JEditorPanes in a JDialog. The first JEditorPane displays an HTML document that contains a list of links that can be clicked. The second one displays the URL when the user clicks on a link.

I want to change the color of the clicked link to black, so the user easily recognizes what link he clicked last.

I used this code

  @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);
      }
    }
  }

Sadly this only works when the JEditorPane has the focus. Since I also have a JTextField in my JDialog, that I want to never lose focus, my current solution no longer works.

I tried the solutions offered here, but they did not work in my case.

Edit: Using CSS did not work unfortunately. This the HTML Code that is displayed in my JEditorPane

<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>

but still I don't get the hover effect.

Edit 2: posted my own solution for the problem as answer. Still I'd love to know why CSS didn't work.

Christoph H.
  • 173
  • 1
  • 14

2 Answers2

1

You can use CSS ability Just write this code

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;

}
reza shams
  • 57
  • 4
0

My solution:

private final DefaultHighlightPainter highlightPainterLightGray 
    = new DefaultHighlightPainter(Color.LIGHT_GRAY);

@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
  if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
    myJEditorPane.getHighlighter().removeAllHighlights();
    myJEditorPane.getHighlighter().addHighlight(
      e.getSourceElement().getStartOffset(),
      e.getSourceElement().getEndOffset(), highlightPainterLightGray);
  }
}

This doesn't change the color of the font like I initially wanted, but changes the background color instead. This also gives the user a good feeling for what link he clicked last and that was my goal.

Christoph H.
  • 173
  • 1
  • 14