【问题标题】:How to trigger a hyperlink using a keystroke in a Swing JEditorPane如何在 Swing JEditorPane 中使用击键触发超链接
【发布时间】:2009-10-02 11:56:51
【问题描述】:

我正在尝试使用“Enter”键在 JEditorPane 中触发超链接。这样插入符号下的超链接(如果有)就会触发,而不必用鼠标单击。

任何帮助将不胜感激。

【问题讨论】:

  • 我还没有真正接近这个。已经搜索了 swing 文档,看看我是否可以从编辑器获得链接列表,所以也许我可以浏览每个链接,看看它是否在插入符号下,但我找不到这样的列表。

标签: java swing jeditorpane


【解决方案1】:

首先,HyperlinkEvent 仅在不可编辑的 JEditorPane 上触发,因此用户很难知道插入符号何时位于链接上。

但如果您确实想这样做,那么您应该使用键绑定(而不是 KeyListener)将 Action 绑定到 ENTER KeyStroke。

执行此操作的一种方法是通过在按下 Enter 键时将 MouseEvent 分派到编辑器窗格来模拟鼠标单击。像这样的:

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) {}
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2010-11-15
    • 2016-06-18
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多