在按下Enter键时(在JTextPane中)添加一个字符(或一个字符串) [英] Add a character (or a String) when enter is pressed (in a JTextPane)

查看:91
本文介绍了在按下Enter键时(在JTextPane中)添加一个字符(或一个字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 JTextPane ,并添加了一个keyListener,这样我就可以知道是否按下了Enter键:

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

但是现在我不知所措,如何在textPane中添加字符'}'?
(不在光标位置之后的任何位置,直到以下位置...)

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

推荐答案

如@HovercraftFullOfEels在上面的注释中所建议,请勿使用KeyListener来监听 enter 键,使用 KeyBindings 答案,它使用键绑定,尽管它不带JTextPane,但您可以从在那里.

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.

这篇关于在按下Enter键时(在JTextPane中)添加一个字符(或一个字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆