简体   繁体   English

在javafx中的文本字段中添加特殊字符

[英]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" 或在数字中的某些数字之间添加一些空格,例如:“ 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. 您可以使用textfield.getCaratPosition()查找当前位置,并使用textfield.positionCarat(...)进行更改。

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? 复制和粘贴呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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