Java 如何在Swing窗格中使用击键触发超链接
我正试图使用“回车”键在绝地武士窗格中触发超链接。这样插入符号下的超链接(如果有)将触发,而不必用鼠标单击Java 如何在Swing窗格中使用击键触发超链接,java,swing,jeditorpane,Java,Swing,Jeditorpane,我正试图使用“回车”键在绝地武士窗格中触发超链接。这样插入符号下的超链接(如果有)将触发,而不必用鼠标单击 任何帮助都将不胜感激。首先,HyperlinkEvent仅在不可编辑的JEditorPane上启动,因此用户很难知道插入符号何时在链接上 但是如果您确实想这样做,那么应该使用键绑定(而不是键侦听器)将操作绑定到ENTER击键 一种方法是在按下Enter键时,通过向编辑器窗格发送MouseEvent来模拟鼠标单击。大概是这样的: class HyperlinkAction extends T
任何帮助都将不胜感激。首先,HyperlinkEvent仅在不可编辑的JEditorPane上启动,因此用户很难知道插入符号何时在链接上 但是如果您确实想这样做,那么应该使用键绑定(而不是键侦听器)将操作绑定到ENTER击键 一种方法是在按下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) {}
}
}
}
首先,HyperlinkEvent只在不可编辑的JEditorPane上启动,因此用户很难知道插入符号何时在链接上 但是如果您确实想这样做,那么应该使用键绑定(而不是键侦听器)将操作绑定到ENTER击键 一种方法是在按下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) {}
}
}
}
我甚至还没有接近这一点。我已经搜索了swing文档,看看是否可以从编辑器中获得链接列表,所以也许我可以查看每个链接,看看它是否在插入符号下,但我找不到这样的列表。我甚至还没有接近这个列表。我已经搜索了swing文档,看看是否可以从编辑器中获得链接列表,所以也许我可以查看每个链接,看看它是否在插入符号下,但我找不到这样的列表。