JavaFX TextField Array max length of text value

后端 未结 1 416
轻奢々
轻奢々 2021-01-24 07:04

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

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 07:52

    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 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 createLimitedTextFields(int num, int maxLength) {
        final List fields = new ArrayList<>();
    
        final UnaryOperator 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);
      }
    }
    

    0 讨论(0)
提交回复
热议问题