JavaFX TextField: Alternative for Swing InputVerifier?

前端 未结 2 1136
情歌与酒
情歌与酒 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 integerStringConverter = new IntegerStringConverter();
        UnaryOperator filter = getFilter();
        setTextFormatter(new TextFormatter<>(integerStringConverter, null, filter));
        setOnAction(event -> integerStringConverter.fromString(this.getText()));
    }
    
    private UnaryOperator 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());
    }
    
    }
    

提交回复
热议问题