我正在使用FXML设置表单,但是我需要在文本字段中设置字符数限制。我该怎么做?
最佳答案
这是我限制文本字段长度的解决方案。
我不建议使用监听器(在text属性或length属性上)的解决方案,因为它们在所有情况下(在我所看到的情况下)都无法正常运行。
我创建一个最大长度的HTML输入文本,并将其与JavaFX中的文本字段进行比较。在两种情况下,粘贴操作(Ctrl + V),取消操作(Ctrl + Z)都具有相同的行为。此处的目标是在修改文本字段之前检查文本是否有效。
我们可以对数字文本字段使用类似的方法。
import java.util.Objects;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.control.TextField;
public class LimitedTextField extends TextField {
private final IntegerProperty maxLength;
public LimitedTextField() {
super();
this.maxLength = new SimpleIntegerProperty(-1);
}
public IntegerProperty maxLengthProperty() {
return this.maxLength;
}
public final Integer getMaxLength() {
return this.maxLength.getValue();
}
public final void setMaxLength(Integer maxLength) {
Objects.requireNonNull(maxLength, "Max length cannot be null, -1 for no limit");
this.maxLength.setValue(maxLength);
}
@Override
public void replaceText(int start, int end, String insertedText) {
if (this.getMaxLength() <= 0) {
// Default behavior, in case of no max length
super.replaceText(start, end, insertedText);
}
else {
// Get the text in the textfield, before the user enters something
String currentText = this.getText() == null ? "" : this.getText();
// Compute the text that should normally be in the textfield now
String finalText = currentText.substring(0, start) + insertedText + currentText.substring(end);
// If the max length is not excedeed
int numberOfexceedingCharacters = finalText.length() - this.getMaxLength();
if (numberOfexceedingCharacters <= 0) {
// Normal behavior
super.replaceText(start, end, insertedText);
}
else {
// Otherwise, cut the the text that was going to be inserted
String cutInsertedText = insertedText.substring(
0,
insertedText.length() - numberOfexceedingCharacters
);
// And replace this text
super.replaceText(start, end, cutInsertedText);
}
}
}
}
经过JavaFX 8和Java 8u45测试
关于javafx - 如何限制javafx文本字段的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22714268/