5

我有一个 JTextArea。我有一个函数可以在调用某种组合时选择一定数量的文本。它做得很好。The thing is, I want to move caret to the selection beginning when some text is selected and VK_LEFT is pressed. KeyListener 已正确实现,我以其他方式对其进行了测试。问题是,当我编写以下代码时:

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

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

4

1 回答 1

8

这是一个代码片段

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

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

于 2011-05-10T14:39:42.150 回答