JavaFX: when tabed to the textarea, place the insert / cursor at the end of the textarea
(searching on stack overflow, I see that this problem is aimed at JavaScript rather than JavaFX)
I have a textarea that is actually the main text editor in a word processor like application (that is, I intend to let users spend a lot of time working in this textarea) When users select textarea, I want to place the cursor at the end of the textarea so that users can continue editing from the end of their last entry
I implemented it using changelistener (the following code), which has the required behavior However, since the cursor is placed at the end of the textarea every time I get focus, if I want to switch applications and then switch back, the cursor will move For example, if users type a sentence somewhere in the middle of the textarea, switch to reading e-mail, and then switch back to find that their cursor has moved, this is inconvenient
Is there a focus traversal policy that performs this operation or implements this operation in other ways so that the cursor moves to the end only when the user selects textarea? In my opinion, this is usually the desired behavior: whenever the textarea is selected, the cursor always appears at the end of the textarea, but whether or not the cursor remains stationary
TextArea passageTextArea; passageTextArea.focusedproperty().addListener(new changelistener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable,Boolean oldValue,Boolean newValue) { if (newValue.booleanValue()) { passageTextArea.positionCaret(passageTextArea.getText().length()); } } });
Solution
You can add an EventHandler for keyevent. When you press tab, it will move the caret to the end of the text:
EventHandler<KeyEvent> tabListener = evt -> { if (evt.getCode() == KeyCode.TAB && !evt.isShiftDown()) { evt.consume(); passageTextArea.requestFocus(); passageTextArea.end(); } }; node.addEventHandler(KeyEvent.ANY,tabListener);