I am working on a JavaFX project and I have a problem using the TextField control. I want to limit the characters that users will enter to each TextField to one. I found a solut
This is a solution without a GridPane, but this is an easy process of adding the Fields also to a GridPane. And now with a TextFormatter that is much better.
import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ChangeListenerDemo extends Application {
@Override
public void start(Stage primaryStage) {
List<TextField> fields = createLimitedTextFields(9, 1);
VBox box = new VBox();
box.getChildren().addAll(fields);
Scene scene = new Scene(box, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
private List<TextField> createLimitedTextFields(int num, int maxLength) {
final List<TextField> fields = new ArrayList<>();
final UnaryOperator<TextFormatter.Change> filter
= (TextFormatter.Change change) -> {
if (change.getControlNewText().length() > maxLength) {
return null;
}
return change;
};
for (int i = 0; i < num; i++) {
final TextField tf = new TextField();
tf.setTextFormatter(new TextFormatter(filter));
fields.add(tf);
}
return fields;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}