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. E.g. what if the text is changing because the user deletes something? What about copy and paste?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top