Pergunta

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

}

Foi útil?

Solução

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?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top