2009-10-01 79 views
0

我試圖使用「Enter」按鍵在JEditorPane中觸發超鏈接。因此插入符號下的超鏈接(如果有的話)將會啓動,而不必用鼠標點擊。如何在Swing中使用按鍵觸發超鏈接JEditorPane

任何幫助,將不勝感激。

+0

我還沒有真正接近這一個。已經瀏覽了swing文檔,看看能否從編輯器獲得鏈接列表,所以也許我可以查看每個鏈接,看看它是否在插入符號下,但我找不到這樣的列表。 – Ben 2009-10-01 21:50:13

回答

5

首先,HyperlinkEvent僅在不可編輯的JEditorPane上觸發,因此用戶很難知道插入符號何時位於鏈接上。

但是,如果您確實想這樣做,那麼您應該使用鍵綁定(而不是KeyListener)將一個操作綁定到ENTER KeyStroke。

執行此操作的一種方法是通過在按下Enter鍵時將MouseEvent分派到編輯器窗格來模擬mouseClick。這樣的事情:

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

正是我之後,謝謝。 – Ben 2009-10-02 05:07:09