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

旧巷老猫 提交于 2019-12-20 07:46:38

问题


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...)


回答1:


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.



来源:https://stackoverflow.com/questions/44550511/add-a-character-or-a-string-when-enter-is-pressed-in-a-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!