javafx - How to control Caret position in trimmed TextField? -
i have textfield
, in check after changes made. trim away double spaces typed. problem after replace text trimmed one, caret
position refreshes. added calculating, caret
go position user last input, it's not working spaces. code:
eventhandler<inputevent> fieldchangelistener = new eventhandler<inputevent>() { public void handle(inputevent event) { textfield field = (textfield) event.getsource(); int caretpos = field.getcaretposition(); string text = field.gettext(); text = text.replaceall("\\s+", " ").trim(); field.settext(text); field.positioncaret(caretpos); event.consume();}}; name.addeventhandler(keyevent.key_released, fieldchangelistener);
in picture user puts cursor before word 'friend', presses space bar , space trimmed, placing caret
right after 'f'. if space bar hold longer, caret
placed in end.
desired result: caret placed before word 'friend'.
how better that?
the reason why caret position not working expected because not reducing caret position when there multiple space in string. should remove caret position amount of removed multiple spaces.
in code below, check if string has @ least double spaces , if remove spaces , reduce caret position number of spaces removed string.
import javafx.application.application; import javafx.event.eventhandler; import javafx.scene.scene; import javafx.scene.control.textfield; import javafx.scene.input.inputevent; import javafx.scene.input.keyevent; import javafx.scene.layout.anchorpane; import javafx.stage.stage; public class miner extends application { @override public void start(stage primarystage) throws exception { anchorpane pane = new anchorpane(); textfield tf = new textfield("hello friend"); int caretpos = tf.getcaretposition(); system.out.println("caretpos = " + caretpos); pane.getchildren().add(tf); eventhandler<inputevent> fieldchangelistener = new eventhandler<inputevent>() { public string atleastdoublespace = " "; public void handle(inputevent event) { textfield field = (textfield) event.getsource(); string text = field.gettext(); string originalstring = text; int caretpos; if(text.contains(atleastdoublespace)) { caretpos = field.getcaretposition(); text = text.replaceall("\\s+"," ").trim(); field.settext(text); int spacesremoved = originalstring.length() - text.length(); field.positioncaret(caretpos - spacesremoved); event.consume(); } else { caretpos = field.getcaretposition(); field.settext(text); field.positioncaret(caretpos); event.consume(); } }}; tf.addeventhandler(keyevent.key_released, fieldchangelistener); scene scene = new scene(pane); primarystage.setscene(scene); primarystage.show(); } public static void main(string[] args) { launch(args); } }
i provided solution depending upon understanding question provided. let me know, if need further help.
Comments
Post a Comment