简体   繁体   中英

add a special character to a text field in javafx

I want to add a special character to a textfield . For example I want to add / automatically between a date that user typed. Or adding some space between some digits in a number .like this: "2020 2020 2020 2020"

I used this code but it doesn't work correctly .

textfield.textProperty().addListener(new ChangeListener<String>(){
  @Override
 public void changed(ObservableValue<? extends String> ov, String t, String t1) {
       if(t1.length()==4 || t1.length()==9 || t1.length()==14){
          textfield.setText(t1+" ");
           System.out.println("space added");
    }
}

}

It's adding the space just fine. I think the issue is that you want to move the carat position after adding the extra text. You can use textfield.getCaratPosition() to find the current position and textfield.positionCarat(...) to change it.

The logic is going to be quite complex though and depends greatly on what the user is doing and precisely how you want the text field to behave. Eg what if the text is changing because the user deletes something? What about copy and paste?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM