javafx - 如何限制javafx文本字段的字符数

标签 javafx fxml

我正在使用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/

相关文章:

text - 如何在 JavaFX 的文本字段中添加提示文本

javafx - 填充 FXML 中定义的选择框

javafx - 如何在javaFX中使 Canvas 可调整大小?

加载 FXML 时发生 javafx.fxml.LoadException

java - 如何在具有两个场景的 JavaFXML Controller 中初始化圆形对象的双数组?

JavaFX - 场景中的居中文本

macos - 不带 JRE 的 Netbeans javafx mac bundle

java - 节点移动 - JavaFX

JavaFX 8 : Populating a TableView in initialize method

css - 文本对齐对齐但向右