JavaFX:TextField ...将字符输入限制为double(无多个逗号)

时间:2017-04-09 14:28:02

标签: javafx textfield

在TextField中,只允许用户输入双号,例如" 12345,12"或" 123456" 问题是不幸的是,可以多次输入逗号字符,例如, " 12345,12 ,,, 34"

如何将逗号数量限制为最多1倍?

我到目前为止:

public class MyTextFieldOnlyDoubleWithComma extends TextField {

  public boolean ifCondition_validate(String text) {
      boolean retValue = false;
      retValue = ( text.matches("[0-9,]*" ) );
      return retValue;
  }

  @Override
  public void replaceText(int start, int end, String text) {
      if ( ifCondition_validate(text) ) {
          super.replaceText(start, end, text);
      }     
  } 

  @Override
  public void replaceSelection(String text) {
       if ( ifCondition_validate(text) ) {
          super.replaceSelection(text);
      }
  }
}

中间体:
非常感谢您的帮助。不幸的是,这种情况并非如此。因为你不能输入",":

public boolean ifCondition_validate(String text) {
    boolean retValue = false;       

    //Necessary to delete characters in Edit mode
    if(text.equals("")) { return true; }

    String text_doubleWithPoint = text.replace(",", "."); //x,yz => x.yz
    try {           
        Double.parseDouble(text_doubleWithPoint);
        retValue=true;
        System.out.println(">Input: '" + text + "' ... ok<");
    } catch(NumberFormatException e){
        System.out.println(">Input: '" + text + "' ... not allowed<");
    }

   return retValue;
}

1 个答案:

答案 0 :(得分:6)

使用带有过滤器的TextFormatter来阻止导致无效文字的输入:

TextField textField = new TextField();

Pattern pattern = Pattern.compile("\\d*|\\d+\\,\\d*");
TextFormatter formatter = new TextFormatter((UnaryOperator<TextFormatter.Change>) change -> {
    return pattern.matcher(change.getControlNewText()).matches() ? change : null;
});

textField.setTextFormatter(formatter);