2009-10-01 1 views
0

"Enter"키 스트로크를 사용하여 JEditorPane에서 하이퍼 링크를 시작하려고합니다. 하이퍼 링크가있는 경우 마우스가 클릭하는 것보다는 캐럿 아래의 하이퍼 링크가 실행됩니다.Swing JEditorPane 키 스트로크 (keystroke)를 사용하여 하이퍼 링크를 트리거하는 방법

도움을 주시면 감사하겠습니다.

+0

나는 이것에 대해서 정말로 가까이 있지 않았다. 스윙 워드 프로세서를 샅샅이 뒤져서 편집기에서 링크 목록을 얻을 수 있는지 확인해 보았습니다. 각 링크를 통해 캐럿 아래 있는지 확인할 수 있지만 그런 목록을 찾을 수는 없습니다. – Ben

답변

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