Search code examples
javaswingjtextpane

Add a character (or a String) when enter is pressed (in a JTextPane)


So I have a JTextPane and I added a keyListener, like that I can know if the enter button was pressed :

JTextPane textPane = new JTextPane();

textPane.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
        }
        @Override
        public void keyPressed(KeyEvent e) {

            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // add there the code to add a character to the textPane!
            }
        }
        @Override
        public void keyReleased(KeyEvent e) {
        }
    });

But now I am bloked, how to add a character '}' to the textPane?
(not anywhere, just after the cursor's position, to the following...)


Solution

  • As suggested in the comments above by @HovercraftFullOfEels, don't use a KeyListener to listen to the enter key, instead use KeyBindings or a DocumentListener. Here's an answer from Hovercraft that uses Key Bindings, though it's not with a JTextPane but you can take the general idea from there.

    To append text in the caret position, you could try JTextPane#replaceSelection(String) which from the docs:

    Replaces the currently selected content with new content represented by the given string. If there is no selection this amounts to an insert of the given text. If there is no replacement text this amounts to a removal of the current selection. The replacement text will have the attributes currently defined for input at the point of insertion. If the document is not editable, beep and return.