按Ctrl + C时,将字符串打印到JEditorPane中的插入位置

时间:2012-07-16 14:28:57

标签: java keyevent jeditorpane bufferedwriter getcaretpos

当按下CTRL + C时,我正在尝试将某个字符串打印到JEditorPane中的当前插入符号位置。我不确定如何处理两个关键事件并打印到当前的插入位置。 API没有很好地描述它们。我认为它会是这样的:

@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"));
}

有人可以告诉我这是否有效?

1 个答案:

答案 0 :(得分: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);
}

}