Search code examples
javaswingjeditorpane

How to trigger a hyperlink using a keystroke in a Swing JEditorPane


I'm trying to fire hyperlinks in a JEditorPane using the "Enter" keystroke. So that the hyperlink (if any) under the caret will fire rather than having to click with the mouse.

Any help would be appreciated.


Solution

  • First of all the HyperlinkEvent is only fired on a non-editable JEditorPane so it will be difficult for the users to know when the caret is over a link.

    But if you do want to do this, then you should be using Key Bindings (not a KeyListener) to bind an Action to the ENTER KeyStroke.

    One way to do this is to simulate a mouseClick by dispatching a MouseEvent to the editor pane when the Enter key is pressed. Something like this:

    class HyperlinkAction extends TextAction
    {
        public HyperlinkAction()
        {
            super("Hyperlink");
        }
    
        public void actionPerformed(ActionEvent ae)
        {
            JTextComponent component = getFocusedComponent();
            HTMLDocument doc = (HTMLDocument)component.getDocument();
            int position = component.getCaretPosition();
            Element e = doc.getCharacterElement( position );
            AttributeSet as = e.getAttributes();
            AttributeSet anchor = (AttributeSet)as.getAttribute(HTML.Tag.A);
    
            if (anchor != null)
            {
                try
                {
                    Rectangle r = component.modelToView(position);
    
                    MouseEvent me = new MouseEvent(
                        component,
                        MouseEvent.MOUSE_CLICKED,
                        System.currentTimeMillis(),
                        InputEvent.BUTTON1_MASK,
                        r.x,
                        r.y,
                        1,
                        false);
    
                    component.dispatchEvent(me);
                }
                catch(BadLocationException ble) {}
            }
        }
    }