How can I allow a user to add hyperlinks into a JTextPane? Such hyperlinks should behave like those found in JEditorPane with HTML documents.
Created May 4, 2012
Sandip Chitale Well you may allow the user to enter the text and
the URL in a dialog. Then implement a method -
private int linkID = 0; public void addHyperlink(URL url, String text) { try { SimpleAttributeSet attrs = new SimpleAttributeSet(); StyleConstants.setUnderline(attrs, true); StyleConstants.setForeground(attrs, unvisitedColor); attrs.addAttribute(ID, new Integer(++linkID)); attrs.addAttribute(HTML.Attribute.HREF, url.toString()); doc.insertString(doc.getLength(), text, attrs); } catch (BadLocationException e) { e.printStackTrace(System.err); } }Then also define a mouse and mouse motion listener and do -
public class LinkController extends MouseAdapter implements MouseMotionListener { public void mouseMoved(MouseEvent ev) { JTextPane editor = (JTextPane) ev.getSource(); if (! editor.isEditable()) { Point pt = new Point(ev.getX(), ev.getY()); int pos = editor.viewToModel(pt); if (pos >= 0) { Document doc = editor.getDocument(); if (doc instanceof DefaultStyledDocument) { DefaultStyledDocument hdoc = (DefaultStyledDocument) doc; Element e = hdoc.getCharacterElement(pos); AttributeSet a = e.getAttributes(); String href = (String) a.getAttribute(HTML.Attribute.HREF); if (href != null) { if (isShowToolTip()){ setToolTipText(href); } if (isShowCursorFeedback()) { if (getCursor() != handCursor) { setCursor(handCursor); } } } else { if (isShowToolTip()){ setToolTipText(null); } if (isShowCursorFeedback()) { if (getCursor() != defaultCursor) { setCursor(defaultCursor); } } } } } else { setToolTipText(null); } } /** * Called for a mouse click event. * If the component is read-only (ie a browser) then * the clicked event is used to drive an attempt to * follow the reference specified by a link. * * @param e the mouse event * @see MouseListener#mouseClicked */ public void mouseClicked(MouseEvent e) { JTextPane editor = (JTextPane) e.getSource(); if (! editor.isEditable()) { Point pt = new Point(e.getX(), e.getY()); int pos = editor.viewToModel(pt); if (pos >= 0) { // get the element at the pos // check if the elemnt has the HREF // attribute defined // if so notify the HyperLinkListeners } } } }