Search code examples
javakeyeventjeditorpanebufferedwritergetcaretpos

Print string to Caret position in JEditorPane when Ctrl+C is pressed


I'm trying to print out a certain string to the current caret position in a JEditorPane when CTRL+C is pressed. I'm not sure how to handle two key events and print to current caret position. The APIs do not do a good job of describing them. I figure it would go something like this:

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

Can someone tell me if this would work?


Solution

  • The keyChar for that event will never be equal to both VK_CONTROL and VK_C at the same time. What you want to do is check for the CONTROL key as a modifier to the event. If you want to insert or append text into the editor pane it is probably better to grab the underlying Document object that contains the text and then insert the text into that. If you know that the key event in this context could only have originated from your editor pane you could do something like the following:

    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();
        }
    }
    

    Here is a full example:

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

    }