Java JEditorPane replace selected text with hyperlink

I am writing a program that uses JEditorPane to create a simple editor that uses hyperlinks so that the user can jump between different pages using a simple hyperlink listener.

The problem is, I want the user to be able to select some text and turn it into a link. I found many examples of doing this with the right mouse button, using the mouse position to select an element in the HTMLDocument, but I also want to be able to do this with a keyboard shortcut.

From searching and experimenting, I came up with a method:

public void createLink() {
    HTMLEditorKit kit = new HTMLEditorKit();
    try {
        String text = jEditorPane1.getSelectedText();
        jEditorPane1.replaceSelection("");
        kit.insertHTML((HTMLDocument) jEditorPane1.getDocument(),
                       jEditorPane1.getCaretPosition(), 
                       "<a href=\"" + text + "\">" + text + "</a>", 
                       0, 0, HTML.Tag.A);
    } catch (BadLocationException | IOException ex) {
        Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

      

But something just seems ugly in this question, I don't know what corner cases can cause problems like trying to put a link in a link or overlapping links. Is there a smarter solution that maps the selected text to elements in the html document?

+3


source to share


1 answer


HTMLEditorKit only supports HTML 3.2, so you are likely to run into several problems. If you are targeting HTML tags beyond version 3.2, JavaFX HTMLEditor will work better for you . If you don't want to use JavaFX, then there are Swing alternatives such as SHEF . If you want complete examples from scratch, check out the O'Reilly HTML Editor Kits book (old but instructive).

From the HTMLEditorKit doc :



The default support is provided by this class, which supports HTML version 3.2 (with some extensions) and is carried over towards version 4.0.

The earliest version of HTML that can be checked against XML Schema was XHTML 1.0, so finding all exceptions would be a problem with HTMLEditorKit. You might be able to integrate JTidy .

+1


source







All Articles