add Text Limiter to JavaFX TextField - Java JavaFX

Java examples for JavaFX:TextField

Description

add Text Limiter to JavaFX TextField

Demo Code


//package com.java2s;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;

import javafx.scene.control.TextField;

public class Main {
    public static void addTextLimiter(final TextField tf,
            final int maxLength) {
        tf.textProperty().addListener(new ChangeListener<String>() {
            @Override/*from ww  w  .  jav  a 2 s.co m*/
            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);
                }
            }
        });
    }
}

Related Tutorials