JavaFX:使用TextFormatter从TextField中删除空格
我正在尝试制作一个小程序,在JavaFX中搜索词汇表中的单词。我有一个文本字段,用户可以在其中指定搜索的单词。如果存在空格,则搜索不起作用。我尝试使用TextFormatter删除其中的空格JavaFX:使用TextFormatter从TextField中删除空格,javafx,textfield,Javafx,Textfield,我正在尝试制作一个小程序,在JavaFX中搜索词汇表中的单词。我有一个文本字段,用户可以在其中指定搜索的单词。如果存在空格,则搜索不起作用。我尝试使用TextFormatter删除其中的空格 searchField.setTextFormatter(new TextFormatter<String>((Change change) -> { String newText = change.getControlNewText();
searchField.setTextFormatter(new TextFormatter<String>((Change change) -> {
String newText = change.getControlNewText();
if (newText.matches(" ")) {
change.setText(change.getText().replace(" ", ""));
return change;
}
if (newText.matches("[A-Z]*")) {
change.setText(change.getText().toLowerCase());
return change;
}
return change;
}));
searchField.setTextFormatter(新的TextFormatter((更改)->{
字符串newText=change.getControlNewText();
if(newText.matches(“”){
change.setText(change.getText().replace(“,”);
回报变化;
}
if(newText.matches(“[A-Z]*”)){
change.setText(change.getText().toLowerCase());
回报变化;
}
回报变化;
}));
属性包含编辑后的所有文本。唯一可以匹配“
的情况是,如果您以空的文本字段开始,然后按空格键。与“[A-Z]*”
匹配的唯一情况是文本字段中的所有字符都是大写;如果TextField
的内容是foo
,并且您添加了一个B
,则不匹配
你也需要考虑到这一点
- 用户可以将文本复制并粘贴到
TextField
中,从而导致text
属性包含多个字符
- 可以选择多个字符,固定文本的长度可能与原始编辑不匹配,需要调整选择范围
这应该满足您的需求(或者至少接近您自己完成代码):
TextField TextField=new TextField();
TextFormatter formatter=新的TextFormatter((TextFormatter.Change)->{
String text=change.getText();
//如果添加了文本,请修复文本以符合要求
如果(!text.isEmpty()){
字符串newText=text.replace(“,”).toLowerCase();
int carretPos=change.getCaretPosition()-text.length()+newText.length();
change.setText(newText);
//根据原始添加文本和固定文本中的差异固定carret位置
更改。选择范围(carretPos,carretPos);
}
回报变化;
});
setTextFormatter(格式化程序);
属性包含编辑后的所有文本。唯一可以匹配“
的情况是,如果您以空的文本字段开始,然后按空格键。与“[A-Z]*”
匹配的唯一情况是文本字段中的所有字符都是大写;如果TextField
的内容是foo
,并且您添加了一个B
,则不匹配
你也需要考虑到这一点
- 用户可以将文本复制并粘贴到
TextField
中,从而导致text
属性包含多个字符
- 可以选择多个字符,固定文本的长度可能与原始编辑不匹配,需要调整选择范围
这应该满足您的需求(或者至少接近您自己完成代码):
TextField TextField=new TextField();
TextFormatter formatter=新的TextFormatter((TextFormatter.Change)->{
String text=change.getText();
//如果添加了文本,请修复文本以符合要求
如果(!text.isEmpty()){
字符串newText=text.replace(“,”).toLowerCase();
int carretPos=change.getCaretPosition()-text.length()+newText.length();
change.setText(newText);
//根据原始添加文本和固定文本中的差异固定carret位置
更改。选择范围(carretPos,carretPos);
}
回报变化;
});
setTextFormatter(格式化程序);
TextField textField = new TextField();
TextFormatter<?> formatter = new TextFormatter<>((TextFormatter.Change change) -> {
String text = change.getText();
// if text was added, fix the text to fit the requirements
if (!text.isEmpty()) {
String newText = text.replace(" ", "").toLowerCase();
int carretPos = change.getCaretPosition() - text.length() + newText.length();
change.setText(newText);
// fix carret position based on difference in originally added text and fixed text
change.selectRange(carretPos, carretPos);
}
return change;
});
textField.setTextFormatter(formatter);