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?