繁体   English   中英

在JTextArea中设置插入位置

[英]Setting caret position in JTextArea

我有一个JTextArea。 我有一个函数,在调用某个组合时选择一些文本。 它做得很好。 问题是,我想在选择一些文本并按下VK_LEFT时将插入符号移动到选择位置。 KeyListener正确实现,我以其他方式测试它。 问题是,当我编写以下代码时:

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

并将此侦听器的实例添加到mainarea,选择一些文本(使用我的函数)并按向左箭头键,插入符号位置设置为选择结束...而且我不会在开头...什么是这件事? :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);

注意:不建议重新定义通常安装的键绑定,如任何箭头键,用户可能会非常烦恼;-)更好地寻找一些尚未绑定的键。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM