在JTextArea中设置插入符位置 [英] Setting caret position in JTextArea

查看:118
本文介绍了在JTextArea中设置插入符位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JTextArea.我有一个函数,可以在调用某种组合时选择一定数量的文本.做好了问题是,当某些文本被选中并按下VK_LEFT时,我想将插入符号移至选择开始位置. KeyListener正确实现,我以其他方式对其进行了测试.问题是,当我编写以下代码时:

I have a JTextArea. I have a function that selects some amount of text when some combination is called. It's done properly. The thing is, I want to move caret to the selection beginning when some text is selected and VK_LEFT is pressed. KeyListener is implemented properly, I tested it in other way. The thing is, that when I write following code:

@Override public void keyPressed( KeyEvent e) {
        if(e.getKeyChar()==KeyEvent.VK_LEFT)
            if(mainarea.getSelectedText()!=null)
                mainarea.setCaretPosition(mainarea.getSelectionStart());
    }

并将此侦听器的一个实例添加到mainarea中,(使用我的功能)选择一些文本,然后按向左箭头键,将插入符号的位置设置为选择的结尾...而我不会将它放在开头. .. 怎么了? :S

and add an instance of this listener to mainarea, select some text (using my function) and press left arrow key, the caret position is set to the end of selection... And I wont it to be in the beginning... What's the matter? :S

推荐答案

以下是代码段

    Action moveToSelectionStart = new AbstractAction("moveCaret") {

        @Override
        public void actionPerformed(ActionEvent e) {
            int selectionStart = textComponent.getSelectionStart();
            int selectionEnd = textComponent.getSelectionEnd();
            if (selectionStart != selectionEnd) {
                textComponent.setCaretPosition(selectionEnd);
                textComponent.moveCaretPosition(selectionStart);
            }
        }

        public boolean isEnabled() {
            return textComponent.getSelectedText() != null;
        }
    };
    Object actionMapKey = "caret-to-start";
    textComponent.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), actionMapKey);
    textComponent.getActionMap().put(actionMapKey, moveToSelectionStart);

注意:不建议您重新定义通常安装的键绑定,例如f.i.任何箭头键,都可能使用户感到非常烦恼;-)最好查找尚未绑定的内容.

Note: it's not recommended to re-define typically installed keybindings like f.i. any of the arrow keys, users might get really annoyed ;-) Better look for some that's not already bound.

这篇关于在JTextArea中设置插入符位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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