【问题标题】:How to format JFXTextField to add spaces on every two characters?如何格式化 JFXTextField 以在每两个字符上添加空格?
【发布时间】:2017-08-12 21:37:52
【问题描述】:

您好,我正在尝试向我的文本字段添加空格格式功能(我正在使用 JFoenix),我的目标是将 100000 写为 10 00 001000000 写为 1 00 00 00

这是我的尝试,但我的结果是相反的,因为插入符号失去了位置。

public static void setup(JFXTextField textField) {
    textField.setOnKeyReleased(value->{
         String entredText = textField.getText();
         String noSpaced = entredText.replaceAll("\\s+","");
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < noSpaced.length(); i++) {
             builder.append(noSpaced.charAt(i));
             if (i%2==0) {
                 builder.append(" ");
             }
         }
         textField.setText(builder.toString());
      });
}

为了测试我在这里面临的问题是:空格太多,文字颠倒了

感谢 Armel Sahamene 的回答,我们解决了间距问题,但没有解决倒车问题

123456 应该是 12 34 56 但结果是 65 43 21

谢谢

【问题讨论】:

    标签: javafx formatting textfield jfoenix


    【解决方案1】:

    可能的解决方案已经回答here

    对于您的情况,我建议使用MaskField

    【讨论】:

    • 我使用 Jfoenix maskfield 很棒,但不是理想的解决方案
    【解决方案2】:

    您的格式取决于 noSpaced 字符串的长度。所以像这样修复你的 if 条件:

    public static void setup(JFXTextField textField) {
    textField.setOnKeyReleased(value->{
         String entredText = textField.getText();
         String noSpaced = entredText.replaceAll("\\s+","");
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < noSpaced.length(); i++) {
             builder.append(noSpaced.charAt(i));
             if ((i % 2 == 0 && noSpaced.length() % 2 == 1) || (i % 2 == 1 && noSpaced.length() % 2 == 0)) {
                 builder.append(" ");
             }
         }
         textField.setText(builder.toString());
      });
    

    }

    【讨论】:

    • 这里的问题是仍然存在反转格式问题尝试写入应该是 12 39 87 的 123987 但你会得到 78 93 21 如何解决这个问题?知道是由于插入符号位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多