【问题标题】:JAVAFx TextField Validation Decimal valueJAVAFx TextField Validation 十进制值
【发布时间】:2017-03-21 23:56:05
【问题描述】:

我试图限制十进制数的文本字段,我已经找到了整数验证的解决方案here,但问题是我无法将以下代码转换为十进制数,例如 324.23、4.3 , 4, 2, 10.43。 (只允许 1 个小数点)。

 vendorList_textField_remaining.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!newValue.matches("\\d*")) {
                vendorList_textField_remaining.setText(newValue.replaceAll("[^\\d||.]", ""));
            }
        }
    });

我也在寻找替代解决方案。 谢谢。

【问题讨论】:

  • 我想如果你想替换第二个“。”,你需要一个“看后面”
  • 为什么不使用微调器?
  • 场景是什么?请提供一个测试用例。另外,试试.replaceAll("^(\\d*\\.)|\\D", "$1")
  • @WiktorStribiżew 嗯,也许.replaceAll("^(\\d*\\.\\d*)\\.", "$1") 会做得更好......
  • 替代解决方案:DoubleTextField from scenebuider

标签: java regex javafx


【解决方案1】:

jidefx-oss 项目中有一些出色的字段验证组件,包括一个用于十进制数字的组件。

【讨论】:

  • 我已经从 cmets 的 @WiktorStribizew 那里得到了正确的答案,谢谢。
【解决方案2】:

我尝试了这种方法: (1) 在 Textfield 上 - 设置一个 EventHandler (2) 在handler中调用一个实用方法来判断Key是否有效

设置处理程序:

txtField_Rate.setOnKeyTyped(new EventHandler<KeyEvent>() 
{
    @Override
    public void handle(KeyEvent ke) 
    {
        String character = ke.getCharacter();
        String text = txtField_Rate.getText();

         if ( !LM_Utility.isValid_forDouble(text, character, 99.99) )
             ke.consume(); 
    }
});

需要 2 个实用功能:- (1) isValidForDouble

public static boolean isValid_forDouble( String oldText, String newChar, double limit )
{
    boolean valid = false;
    String newText = oldText + newChar;
    int maxDecimals = getDecimals(limit);
    int decimals = 0;

    if ( newChar.matches("[0-9]") )
    {
        decimals = getDecimals(newText);
        if ( Double.valueOf(newText) <= limit )
            if ( decimals <= maxDecimals )
                valid = true;     
    }

    if ( newChar.equals(".") )
    {
        if ( !oldText.contains(".") )
                valid = true;
    }                

    return valid;
} 

和 (2) getDecimals()

private static int getDecimals(String value)
{
    int integerPlaces = 0;
    int decimalPlaces = 0;

    if (value.contains("."))
    {
        integerPlaces = value.indexOf('.');
        decimalPlaces = value.length() - integerPlaces - 1;
    }

    return decimalPlaces;
}

【讨论】:

    【解决方案3】:

    我也遇到过同样的情况。我想我已经找到了解决这个问题的方法。正则表达式必须被一个新的替换,并且由 setText 进行一些更改。目前它运作良好。代码如下:

    vendorList_textField_remaining.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if (!newValue.matches("\\d*(\\.\\d*)?")) {
                    vendorList_textField_remaining.setText(oldValue);
                }
            }
        });
    

    【讨论】:

      【解决方案4】:

      感谢您的帮助。我已经用解决方案 (1) 解决了我的问题。

      vendorList_textField_remaining.textProperty().addListener(new ChangeListener<String>() {
          @Override
          public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
              if(!newValue.matches("\\d*(\\.\\d*)?")) {
                  vendorList_textField_remaining.setText(oldValue);
              }
          }
      });
      

      【讨论】:

        【解决方案5】:

        我知道这是个老问题,但我遇到了同样的问题并找到了更好的解决方案。我基于this answer 创建了简单的十进制字段。

        它处理带有负值的小数。您可以放置​​和删除点或 - 即使您已经输入了一些数字,所以这非常友好。

        它还只编译一次模式以确保更好的性能(使用 text.matches("regex") 模式时,每次有人键入字符时都会编译一次)。

        当您声明此类时,您可以在 fxml 文件中使用它,就像它是标准 JavaFX 组件一样。

        public class DecimalField extends TextField {
        
        private static Pattern decimalPattern = Pattern.compile("[-]?[0-9]*(\\.[0-9]*)?");
        
        @Override
        public void replaceText(int start, int end, String text) {
            if (validate(start, text)) {
                super.replaceText(start, end, text);
            }
        }
        
        @Override
        public void replaceSelection(String text) {
            if (validate(Integer.MAX_VALUE, text)) {
                super.replaceSelection(text);
            }
        }
        
        private boolean validate(int start, String text) {
            String currentText = isNull(getText()) ? "" : getText();
            if(start == 0) { //to handle "-1.1" or ".1" cases
                return decimalPattern.matcher(text + currentText).matches();  
            } else {
                return decimalPattern.matcher(currentText + text).matches();
            }
        }
        
        }
        

        当您将模式更改为“[-][0-9]”时,它也适用于整数

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-02
          • 1970-01-01
          • 2018-07-26
          • 1970-01-01
          • 1970-01-01
          • 2014-11-30
          • 2016-02-04
          • 2014-02-05
          相关资源
          最近更新 更多