JavaFX 2.2 TextField maxlength

2019-01-18 13:53发布

I am working with a JavaFX 2.2 project and I have a problem using the TextField control. I want to limit the characters that users will enter to each TextField but I can't find a property or something like maxlength. The same problem was existing to swing and was solved with this way. How to solve it for JavaFX 2.2?

8条回答
2楼-- · 2019-01-18 14:23

This is a better way to do the job on a generic text field:

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);
            }
        }
    });
}

Works perfectly, except for that Undo bug.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-18 14:26

This method let TextField to finish all processing (copy/paste/undo safe). Do not requares to make extending class. And allow you to deside what to do with new text after every change (to push it to logic, or turn back to previous value, or even to modify it).

  // 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 your case just add this logic inside. Works perfectly.

    // For example 10 characters     
  if (newValue.length() >= 10) ((StringProperty)observable).setValue(oldValue);
查看更多
登录 后发表回答