JavaFX TextField: Alternative for Swing InputVerifier?

前端 未结 2 1137
情歌与酒
情歌与酒 2021-01-25 08:44

I am looking for an alternative of Swing InputVerifier to JavaFX TextField.

The Swing InputVerifier will prevent input that does verify.

Consider the following S

相关标签:
2条回答
  • 2021-01-25 09:29

    I have IntegerField control with StringConverter, UnaryOperator and TextFormatter. Maybe helpful for you!

    import javafx.scene.control.TextField;
    import javafx.scene.control.TextFormatter;
    import javafx.util.StringConverter;
    import javafx.util.converter.IntegerStringConverter;
    import java.util.function.UnaryOperator;
    
    public class IntegerField extends TextField {
    
    public IntegerField() {
        super();
        StringConverter<Integer> integerStringConverter = new IntegerStringConverter();
        UnaryOperator<TextFormatter.Change> filter = getFilter();
        setTextFormatter(new TextFormatter<>(integerStringConverter, null, filter));
        setOnAction(event -> integerStringConverter.fromString(this.getText()));
    }
    
    private UnaryOperator<TextFormatter.Change> getFilter() {
        return change -> {
            String text = change.getText();
            if (!change.isContentChange()) {
                return change;
            }
            if (text.matches("[0-9]*")) {
                return change;
            }
            return null;
        };
    }
    
    public Integer getValue() {
        return Integer.valueOf(this.getText());
    }
    
    }
    
    0 讨论(0)
  • 2021-01-25 09:39

    As first suggested by James_D a TextFormatter with filter was the solution.

    TextField instance = new TextField();
    UnaryOperator<Change> textFilter = change -> {
        String input = change.getText();
        if (!change.isContentChange()) {
            return change;
        }
        if (!myRegExTool.matches(input)) {
            return null;
        }
        return change;
    };
    instance.setTextFormatter(new TextFormatter<String>(textFilter));
    
    0 讨论(0)
提交回复
热议问题