简体   繁体   中英

Java JEditorPane replace selected text with a hyperlink

I'm writing a program which uses a JEditorPane to make a simple editor, it uses hyperlinks to allow the user to jump between different pages using a simple hyperlink listener.

The problem is I want to have the ability to have a user select some text and turn it into a link. I found lots of examples doing this on right click using the position of the mouse to select the element in the HTMLDocument but I also want it to be possible to do it via a keyboard shortcut.

From searching and experimenting I came up with the 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 about this, I've no idea what corner cases are going to cause problems such as trying to put a link within a link, or overlapping links. Is there a more sensible solution that maps the selected text to elements in the html document?

HTMLEditorKit only supports HTML 3.2, so you will likely encounter several issues. If you are targeting HTML tags beyond version 3.2, then you will be better served by JavaFX HTMLEditor . If you do not want to use JavaFX, then there are alternative implementations for Swing, such as SHEF . If you want some complete examples from scratch, try the O'Reilly HTML Editor Kits book (old but instructive).

From the HTMLEditorKit documentation:

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

The earliest version of HTML that could be validated against an XML schema was XHTML 1.0, so finding all of the outlier cases will be challenge with HTMLEditorKit. You might have some luck integrating JTidy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM