该事件的 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);
}
}