Mark already used hyperlinks in HTMLEditorKit

118 Views Asked by At

I'm generating a HTML table with the Swing HTMLEditorKit. One column is showing selectable hyperlinks.

Like in search engines I would like to mark links already invoked (bold or by coloring).

Where would be the correct place to add this behaviour?

Edit:

Gilbert, thanks for your hint

It seems that the link state is not respected. The first addRule line is not changing the color but keeps the default blue font. The second commented out line works.

    ...
    HTMLEditorKit kit = new HTMLEditorKit();
    StyleSheet css = kit.getStyleSheet();
    if (css.getStyleSheets() == null) {
        StyleSheet css2 = new StyleSheet();
        css2.addRule("a:link {color: #DDDDDD } a:visited {color: #DDDDDD } a:hover {color: #DDDDDD } a:active {color: #DDDDDD } "); 
//          css2.addRule("a {color: #DDDDDD }"); 
        css2.addStyleSheet(css);
        kit.setStyleSheet(css2);
    }       
1

There are 1 best solutions below

0
On

This one gave me the solution.

A slight modification works for me

    jEditorPane.addHyperlinkListener(new HyperlinkListener() {

            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                HyperlinkEvent.EventType type = e.getEventType();
                
                if (type == HyperlinkEvent.EventType.ACTIVATED) {
                    
                    // mark activated
                    if (e.getSourceElement() != null) {
                        AttributeSet a = e.getSourceElement().getAttributes();
                        AttributeSet anchor = (AttributeSet) a.getAttribute(HTML.Tag.A);
                        if (anchor != null) {
                            //only highlight anchor tags
                            highlightHyperlink(e.getSourceElement());
                        }
                    }