2017-04-09 8 views
0

TextFieldでは、ユーザーはダブル数字のみを入力できます。 "12345,12"または "123456" カンマ文字は残念ながら複数回入力することができます。 "12345,12 ,,, 34"JavaFX:TextField ...文字入力を二重に制限します(複数のコンマはありません)。

どのようにカンマの数を最大1xに制限できますか?

は、私がこれまでに来た:

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; 
} 
+0

あなたはマッチ機能で数字だけを入れて管理しなければなりません』、」離れて。おそらくブール値 – FFdeveloper

答えて

2

は、ブロックの入力が無効な文字が得られていることのフィルターで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); 
+0

ありがとう、それは動作します。 – Sten

関連する問題