天天看點

javaFx文本框設定文本格式

JavaFx在使用TextField文本框時,難免有限制文本格式的需求,這時候小編嘗試使用輸入監聽,輸入框Change監聽事件,本以為完成了,可是在無意間發現在輸入中文時,無法監聽到KeyEvent事件,是以顯得不那麼專業。在網上尋找到了Aimls的視訊,看了之後深受感觸。直接附上代碼:

@FXML
        private TextField textFieldPort;

        this.textFieldPort.setTextFormatter(new TextFormatter<String>(new UnaryOperator<TextFormatter.Change>() {
            @Override
            public TextFormatter.Change apply(TextFormatter.Change change) {
                String value = change.getText();
                if (value.matches("[0-9]*")) {
                    return change;
                }
                return null;
            }
        }));
           

TextField文本框中就有文本格式的接口,是以可以通過setTextFormatter(TextFormatter<?> value)方法實作自定義文本格式限制。

public final void setTextFormatter(TextFormatter<?> value) { textFormatter.set(value); }
           

-在文本失去焦點的時候,可以使用setTextFormatter(StringConverter<V> valueConveryer)方法實作

public TextFormatter(@NamedArg("valueConverter") StringConverter<V> valueConverter) {
        this(valueConverter, null, null);
    }
           

Example:文本框失去焦點時,使用trim()去除前後的空格

@FXML
    private TextField textFieldName;

    this.textFieldName.setTextFormatter(new TextFormatter<String>(new StringConverter<String>() {
            @Override
            public String toString(String object) {
                return object == null ? "" : object;
            }

            @Override
            public String fromString(String string) {
                return string == null ? "" : string.trim();
            }
        }));
           

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

代碼整理如下:

import javafx.scene.control.TextFormatter;

import java.util.function.UnaryOperator;

public class IntUnaryOperator implements UnaryOperator<TextFormatter.Change> {

    @Override
    public TextFormatter.Change apply(TextFormatter.Change change) {
        String value = change.getText();
        if (value.matches("[0-9]*")) {
            return change;
        }
        return null;
    }
}
           
import javafx.util.StringConverter;

public class TrimStringConverter extends StringConverter<String> {
    @Override
    public String toString(String object) {
        return object == null ? "" : object;
    }

    @Override
    public String fromString(String string) {
        return string == null ? "" : string.trim();
    }
}
           
import javafx.scene.control.TextFormatter;

public class MyTextFormatter {
    public MyTextFormatter() {
    }

    public static TextFormatter<String> trimTextFormatter() {
        return new TextFormatter<String>(new TrimStringConverter());
    }

    public static TextFormatter<String> intTextFormatter() {
        return new TextFormatter<String>(new IntUnaryOperator());
    }
}