Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting caret position in JTextArea

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

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

like image 641
nicks Avatar asked May 10 '11 14:05

nicks


1 Answers

Here's a code snippet

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

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.

like image 158
kleopatra Avatar answered Sep 18 '22 23:09

kleopatra