How to apply mask formatting to TextField?

2019-02-12 15:50发布

I am creating some forms and I need to create masks and validation for some fields.

Is it implemented in anyway in JavaFX?

标签: javafx-2
8条回答
Viruses.
2楼-- · 2019-02-12 16:53

Supported by current javafx-2 platform by default - No, but go through this link , it has many insights and sample code for Form validation in javaFX

查看更多
该账号已被封号
3楼-- · 2019-02-12 16:55

In some cases I would validate the text property:

myTextField
    .textProperty()
    .addListener(
    (obs, oldVal, newVal) -> 
        { 
            if(!newVal.matches("\\d+"))
                textField.setText(oldV);
        });

Unlucky: textField.setText(oldV); will enter the same function again, testing unnecessarily if oldVal matches.

If the TextField becomes a value that doesn't matches before this listener is added to the TextField, enter a not matching new value will cause a loop!!!

To avoid this, it will be safer to write:

String acceptableValue = "0";
myTextField
    .textProperty()
    .addListener(
    (obs, oldVal, newVal) -> 
        { 
            if(!newVal.matches("\\d+"))
                textField.setText(oldVal.matches("\\d+") ? oldV : acceptableValue);
        });
查看更多
登录 后发表回答