我有TextFormatter
:
mailTextField.setTextFormatter(new TextFormatter<>(change -> {
int maxLength = 100;
if (change.isAdded()) {
if(change.getControlNewText().length()>maxLength){
if(change.getText().length()==1){
change = null;
System.out.println("Reached max!");
}else{
int allowedLength = maxLength - change.getControlText().length();
change.setText(change.getText().substring(0, allowedLength));
System.out.println("Cut paste!");
}
}
if(change!=null){
System.out.println("Mail check: "+change.getControlNewText());
if(Validation.mail(change.getControlNewText())){
showCorrectIcon(mailTextField);
}else{
showErrorIcon(mailTextField);
}
}
}
return change;
}));
由于初始邮件存储在数据库中,我不想为它显示正确的图标,但仅当用户尝试调整它时。是否可以使TextFormatter
仅在邮件字段成为焦点时才起作用?
答案 0 :(得分:0)
您可以使用isFocused()
功能:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#isFocused--
在TextFormatter的开头你可以这样做:
if (!mailTextField.isFocused()) {
return change;
}
完整示例:
mailTextField.setTextFormatter(new TextFormatter<>(change -> {
if (!mailTextField.isFocused()) {
return change;
}
int maxLength = 100;
if (change.isAdded()) {
if(change.getControlNewText().length()>maxLength){
if(change.getText().length()==1){
change = null;
System.out.println("Reached max!");
}else{
int allowedLength = maxLength - change.getControlText().length();
change.setText(change.getText().substring(0, allowedLength));
System.out.println("Cut paste!");
}
}
if(change!=null){
System.out.println("Mail check: "+change.getControlNewText());
if(Validation.mail(change.getControlNewText())){
showCorrectIcon(mailTextField);
}else{
showErrorIcon(mailTextField);
}
}
}
return change;
}));