该事件的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);
}
}
当我在调试器中运行它时,它捕获了KeyEvent并转到keyPressed()方法,但没有做任何事情,也没有得到任何错误。我使用了在程序开始时初始化的全局JEditorPane,而不是像你一样创建一个新的实例。你知道为什么它还没有做任何事吗? – ridecontrol53 2012-07-16 17:16:19
糟糕,这就是我从内存编码时得到的结果。我把修饰符的错误常量 - 如果你使用那个现在有效的那个,它就会工作。 – Sticks 2012-07-16 17:58:11
非常感谢。很棒。尽管如何将整个'keyPressed()'方法放入'addKeyListener()'内,这种方法有点奇怪。 – ridecontrol53 2012-07-16 18:57:41