我正在尝试使用“Enter”击键在 JEditorPane 中触发超链接。这样插入符号下的超链接(如果有)就会触发,而不必用鼠标单击。
任何帮助,将不胜感激。
我正在尝试使用“Enter”击键在 JEditorPane 中触发超链接。这样插入符号下的超链接(如果有)就会触发,而不必用鼠标单击。
任何帮助,将不胜感激。
首先,HyperlinkEvent 仅在不可编辑的 JEditorPane 上触发,因此用户很难知道插入符号何时位于链接上。
但是,如果您确实想这样做,那么您应该使用键绑定(而不是 KeyListener)将操作绑定到 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) {}
}
}
}