JavaFX:使用 TextFormatter 从 TextField 中删除空格
JavaFX: Remove spaces from TextField using TextFormatter
我正在尝试制作一个小程序,用于在 JavaFX 的词汇表中搜索单词。我有一个 TextField,用户可以在其中指定搜索的词。如果有空格,搜索将不起作用。我尝试使用 TextFormatter 从那里删除空格。
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;
}));
controlNewText
属性 包含编辑后的所有文本。唯一可以匹配 " "
的情况是,如果您以空 TextField
开始并按 space。匹配 "[A-Z]*"
的唯一情况是 TextField
中的所有字符都是大写;它不匹配,如果 TextField
的内容是 foo
而你添加一个 B
.
你还需要考虑到
- 用户可以将文本复制并粘贴到
TextField
中,导致 text
属性 包含多个字符
- 可以选择多个字符,固定文本可能与原始编辑的长度不匹配,需要您调整选择范围
这应该能满足您的要求(或者至少接近您自己完成代码的程度):
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);
我正在尝试制作一个小程序,用于在 JavaFX 的词汇表中搜索单词。我有一个 TextField,用户可以在其中指定搜索的词。如果有空格,搜索将不起作用。我尝试使用 TextFormatter 从那里删除空格。
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;
}));
controlNewText
属性 包含编辑后的所有文本。唯一可以匹配 " "
的情况是,如果您以空 TextField
开始并按 space。匹配 "[A-Z]*"
的唯一情况是 TextField
中的所有字符都是大写;它不匹配,如果 TextField
的内容是 foo
而你添加一个 B
.
你还需要考虑到
- 用户可以将文本复制并粘贴到
TextField
中,导致text
属性 包含多个字符 - 可以选择多个字符,固定文本可能与原始编辑的长度不匹配,需要您调整选择范围
这应该能满足您的要求(或者至少接近您自己完成代码的程度):
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);