2017-04-09 26 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

相關問題