Set carriage position in JTextArea

I have a JTextArea. I have a function that selects a part of the text when a combination is called. This is done correctly. The fact is that I want to move the carriage to the top of the selection when some text is selected and the VK_LEFT key is pressed. KeyListener is implemented correctly, I tested it in another way. The thing is, when I write the following code:

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

and add an instance of this listener to mainarea, select the text (using my function) and press the left arrow key, the carriage position will be set at the end of the selection ... And I will not be at the beginning ... What's the matter ?: S

+5
source share
1 answer

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

+7

All Articles