2012-07-16 36 views
0

我試圖按CTRL + C時將某個字符串打印到JEditorPane中的當前插入符號位置。我不知道如何處理兩個關鍵事件並打印到當前的插入位置。 API不能很好地描述它們。我想它會走這樣的事情:按Ctrl + C時將字符串打印到JEditorPane中的插入位置

@Override 
public void keyPressed(KeyEvent e) { 
    if((e.getKeyChar()==KeyEvent.VK_CONTROL) && (e.getKeyChar()==KeyEvent.VK_C)) 
     //JEditorPane.getCaretPosition(); 
     //BufferedWriter bw = new BufferedWriter(); 
     //JEditorPane.write(bw.write("desired string")); 
} 

有人可以告訴我,如果這會工作嗎?

回答

4

該事件的keyChar永遠不會同時等於VK_CONTROL和VK_C。你想要做的是檢查CONTROL鍵作爲事件的修飾符。如果要插入或追加文本到編輯器窗格中,最好抓住包含文本的基礎Document對象,然後將文本插入到該對象中。如果你知道,在這方面的關鍵事件只可能源於你的編輯窗格中,你可以做一些類似如下:

if (e.getKeyCode() == KeyEvent.VK_C && 
     (e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK) { 
    JEditorPane editorPane = (JEditorPane) e.getComponent(); 
    int caretPos = editorPane.getCaretPosition(); 
    try { 
     editorPane.getDocument().insertString(caretPos, "desired string", null); 
    } catch(BadLocationException ex) { 
     ex.printStackTrace(); 
    } 
} 

這是一個完整的例子:

import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 

import javax.swing.JEditorPane; 
import javax.swing.JFrame; 
import javax.swing.text.BadLocationException; 

public class EditorPaneEx { 

public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    JEditorPane editorPane = new JEditorPane(); 
    editorPane.addKeyListener(new KeyAdapter() { 
     @Override 
     public void keyPressed(KeyEvent ev) { 
      if (ev.getKeyCode() == KeyEvent.VK_C 
        && (ev.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK) { 
       JEditorPane editorPane = (JEditorPane) ev.getComponent(); 
       int caretPos = editorPane.getCaretPosition(); 
       try { 
        editorPane.getDocument().insertString(caretPos, 
          "desired string", null); 
       } catch (BadLocationException ex) { 
        ex.printStackTrace(); 
       } 
      } 
     } 
    }); 
    frame.add(editorPane); 
    frame.pack(); 
    frame.setVisible(true); 
} 

}

+0

當我在調試器中運行它時,它捕獲了KeyEvent並轉到keyPressed()方法,但沒有做任何事情,也沒有得到任何錯誤。我使用了在程序開始時初始化的全局JEditorPane,而不是像你一樣創建一個新的實例。你知道爲什麼它還沒有做任何事嗎? – ridecontrol53 2012-07-16 17:16:19

+0

糟糕,這就是我從內存編碼時得到的結果。我把修飾符的錯誤常量 - 如果你使用那個現在有效的那個,它就會工作。 – Sticks 2012-07-16 17:58:11

+0

非常感謝。很棒。儘管如何將整個'keyPressed()'方法放入'addKeyListener()'內,這種方法有點奇怪。 – ridecontrol53 2012-07-16 18:57:41