JavaFX的2.2文本字段最大长度(JavaFX 2.2 TextField maxlength)

2019-07-20 18:44发布

我有一个JavaFX 2.2的项目工作,我必须使用文本字段控制的问题。 我想限制用户将进入到每个文本字段的字符,但我无法找到一个属性或类似的东西最大长度。 同样的问题在现有的摆动,并解决了这个方式。 如何解决它的JavaFX 2.2?

Answer 1:

这是一个更好的方式做一个普通的文本字段的工作:

public static void addTextLimiter(final TextField tf, final int maxLength) {
    tf.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
            if (tf.getText().length() > maxLength) {
                String s = tf.getText().substring(0, maxLength);
                tf.setText(s);
            }
        }
    });
}

完美的作品,除了那撤消错误。



Answer 2:

随着java8u40我们得到了一类新的TextFormatter:它的主要职责之一是提供一个勾成文本输入的任何变化,然后才会慢慢comitted的内容。 在这种挂钩,我们可以接受/ rejec T或甚至改变提议的变更。

在解决要求OP的自我答案是

  • 规则:限制文本的长度较短的大于n个字符
  • 修改:如果违反规则,保持最后n个字符的输入文本,并在其开始去除多余的字符

使用的TextFormatter,实现这一点的,如:

// here we adjust the new text 
TextField adjust = new TextField("scrolling: " + len);
UnaryOperator<Change> modifyChange = c -> {
    if (c.isContentChange()) {
        int newLength = c.getControlNewText().length();
        if (newLength > len) {
            // replace the input text with the last len chars
            String tail = c.getControlNewText().substring(newLength - len, newLength);
            c.setText(tail);
            // replace the range to complete text
            // valid coordinates for range is in terms of old text
            int oldLength = c.getControlText().length();
            c.setRange(0, oldLength);
        }
    }
    return c;
};
adjust.setTextFormatter(new TextFormatter(modifyChange));

旁白:

  • 修改属性,一边听它的变化可能会导致意想不到的副作用
  • 在关键级别事件打破了所有建议的解决方案(他们不能处理粘贴/程序化的变化


Answer 3:

你可以做一些类似的做法在这里描述的东西: http://fxexperience.com/2012/02/restricting-input-on-a-textfield/

class LimitedTextField extends TextField {

    private final int limit;

    public LimitedTextField(int limit) {
        this.limit = limit;
    }

    @Override
    public void replaceText(int start, int end, String text) {
        super.replaceText(start, end, text);
        verify();
    }

    @Override
    public void replaceSelection(String text) {
        super.replaceSelection(text);
        verify();
    }

    private void verify() {
        if (getText().length() > limit) {
            setText(getText().substring(0, limit));
        }

    }
};


Answer 4:

我用来解决我的问题完整的代码下面的代码。 我扩展了TextField类像谢尔盖Grinev做,我添加一个空的构造。 要设置的maxlength我添加setter方法。 我第一次检查,然后替换文本字段的文本,因为我想禁止将超过最大长度个字符,否则最大长度+ 1个字符将在文本字段的末尾插入和文本字段的第一个字符内将被删除。

package fx.mycontrols;

public class TextFieldLimited extends TextField {  
    private int maxlength;
    public TextFieldLimited() {
        this.maxlength = 10;
    }
    public void setMaxlength(int maxlength) {
        this.maxlength = maxlength;
    }
    @Override
    public void replaceText(int start, int end, String text) {
        // Delete or backspace user input.
        if (text.equals("")) {
            super.replaceText(start, end, text);
        } else if (getText().length() < maxlength) {
            super.replaceText(start, end, text);
        }
    }

    @Override
    public void replaceSelection(String text) {
        // Delete or backspace user input.
        if (text.equals("")) {
            super.replaceSelection(text);
        } else if (getText().length() < maxlength) {
            // Add characters, but don't exceed maxlength.
            if (text.length() > maxlength - getText().length()) {
                text = text.substring(0, maxlength- getText().length());
            }
            super.replaceSelection(text);
        }
    }
}

里面的FXML文件我增加了进口(的该TextFieldLimited类是现有的包装)上的文件的顶部,代之以自定义TextFieldLimited的文本字段标签。

<?import fx.mycontrols.*?>
.  
.  
. 
<TextFieldLimited fx:id="usernameTxtField" promptText="username" />

里面的控制器类

在顶部(财产申报),
@FXML
private TextFieldLimited usernameTxtField;

初始化方法的内部,
usernameTxtField.setLimit(40);

就这样。



Answer 5:

我用一个简单的方法来限制双方的字符数,并迫使数字输入:

public TextField data;
public static final int maxLength = 5;

data.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable,
            String oldValue, String newValue) {
        try {
            // force numeric value by resetting to old value if exception is thrown
            Integer.parseInt(newValue);
            // force correct length by resetting to old value if longer than maxLength
            if(newValue.length() > maxLength)
                data.setText(oldValue);
        } catch (Exception e) {
            data.setText(oldValue);
        }
    }
});


Answer 6:

这种方法让文本字段来完成所有处理(复制/粘贴/撤销安全)。 不要requares进行扩展类。 并允许您deside什么的每一个变化(将其推到逻辑,或将返回到之前的值,甚至修改)后,用新的文本做。

  // fired by every text property change
textField.textProperty().addListener(
  (observable, oldValue, newValue) -> {
    // Your validation rules, anything you like
      // (! note 1 !) make sure that empty string (newValue.equals("")) 
      //   or initial text is always valid
      //   to prevent inifinity cycle
    // do whatever you want with newValue

    // If newValue is not valid for your rules
    ((StringProperty)observable).setValue(oldValue);
      // (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
      //   to anything in your code.  TextProperty implementation
      //   of StringProperty in TextFieldControl
      //   will throw RuntimeException in this case on setValue(string) call.
      //   Or catch and handle this exception.

    // If you want to change something in text
      // When it is valid for you with some changes that can be automated.
      // For example change it to upper case
    ((StringProperty)observable).setValue(newValue.toUpperCase());
  }
);

对于你的情况下,只需添加里面这个逻辑。 完美的作品。

    // For example 10 characters     
  if (newValue.length() >= 10) ((StringProperty)observable).setValue(oldValue);


Answer 7:

下面的代码将重新定位光标,以便用户不会意外覆盖它们的输入。

public static void setTextLimit(TextField textField, int length) {
    textField.setOnKeyTyped(event -> {
        String string = textField.getText();

        if (string.length() > length) {
            textField.setText(string.substring(0, length));
            textField.positionCaret(string.length());
        }
    });
}


Answer 8:

我的代码,只允许数字和限制在JavaFX的文本字段中输入长度此位。

// Event handler for inputPrice
     inputPrice.setOnAction(event2 -> {

            // Obtain input as a String from text field
            String inputPriceStr = inputPrice.getText();

            // Get length of the String to compare with max length
            int length = inputPrice.getText().length();

            final int MAX = 10; // limit number of characters

            // Validate user input allowing only numbers and limit input size
            if (inputPriceStr.matches("[0-9]*") && length < MAX ) {

                 // your code here
             }});


文章来源: JavaFX 2.2 TextField maxlength