gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:18:49 35 4
gpt4 key购买 nike

在 TextField 中,用户只能输入双数,例如“12345,12”或“123456”问题是逗号字符可能会不幸输入多次,例如“12345,12,,,34”

如何将逗号的数量限制为最多 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;
}

最佳答案

使用带有过滤器的 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);

关于JavaFX: TextField ... 将字符输入限制为 double (无多个逗号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43307872/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com