Nik*_*hil 9 javafx input textfield
这似乎问题是重复此.但我的问题是我已经通过两种方式在JavaFX中开发了一个整数文本字段.代码如下
public class FXNDigitsField extends TextField
{
private long m_digit;
public FXNDigitsField()
{
super();
}
public FXNDigitsField(long number)
{
super();
this.m_digit = number;
onInitialization();
}
private void onInitialization()
{
setText(Long.toString(this.m_digit));
}
@Override
public void replaceText(int startIndex, int endIndex, String text)
{
if (text.matches(Constants.DIGITS_PATTERN) || text.equals(Constants.EMPTY_STRING)) {
super.replaceText(startIndex, endIndex, text);
}
}
@Override
public void replaceSelection(String text)
{
if (text.matches(Constants.DIGITS_PATTERN) || text.equals(Constants.EMPTY_STRING)) {
super.replaceSelection(text);
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二种方法是添加一个事件Filter.
给出了代码片段.
// restrict key input to numerals.
this.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
@Override public void handle(KeyEvent keyEvent) {
if (!"0123456789".contains(keyEvent.getCharacter())) {
keyEvent.consume();
}
}
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是诽谤的方式?任何人都可以帮我挑选合适的人吗?
小智 10
在TextField中添加验证的最佳方法是第三种方式.此方法允许TextField完成所有处理(复制/粘贴/撤消安全).它不需要您扩展TextField类.它允许您决定在每次更改后如何处理新文本(将其推送到逻辑,或转回以前的值,甚至修改它).
// fired by every text property changes
textField.textProperty().addListener(
(observable, oldValue, newValue) -> {
// Your validation rules, anything you like
// (! note 1 !) make sure that empty string (newValue.equals(""))
// or initial text is always valid
// to prevent inifinity cycle
// do whatever you want with newValue
// If newValue is not valid for your rules
((StringProperty)observable).setValue(oldValue);
// (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
// to anything in your code. TextProperty implementation
// of StringProperty in TextFieldControl
// will throw RuntimeException in this case on setValue(string) call.
// Or catch and handle this exception.
// If you want to change something in text
// When it is valid for you with some changes that can be automated.
// For example change it to upper case
((StringProperty)observable).setValue(newValue.toUpperCase());
}
);
Run Code Online (Sandbox Code Playgroud)
在您的两种方式中,您不能键入除数字字符之外的字符.但它允许粘贴任何字符(从任何源复制文本和在TextField中粘贴).
进行验证的好方法是在提交之后,
喜欢(对于整数):
try {
Integer.parseInt(myNumField.getText());
} catch(Exception e) {
System.out.println("Non-numeric character exist");
}
Run Code Online (Sandbox Code Playgroud)
(或者你可以使用你的任何组合+上述方法)
JavaFX 有一个用于此用例的类TextFormatter。它可以让你验证之前它是“COMMITED”在调整文本内容textProperty的TextField。
看这个例子:
TextFormatter<String> textFormatter = new TextFormatter<>(change -> {
if (!change.isContentChange()) {
return change;
}
String text = change.getControlNewText();
if (isValid(text)) { // your validation logic
return null;
}
return change;
});
textField.setTextFormatter(textFormatter);
Run Code Online (Sandbox Code Playgroud)