本页面由葡萄牙语机器翻译,可能存在错误。葡萄牙语版本为准。
如何应用 CPF、CEP 或日期掩码
用途。 在用户只输入数字时自动使用分隔符(点、破折号、斜杠)格式化输入,显示为 123.456.789-00,之后再取回纯净的值(12345678900)。
用到的 API
campo.<TextFieldStyle>getStyle().mask("999.999.999-99".toCharArray())— 定义掩码模式。9= 数字位置;其他任何字符都是自动插入的字面量(.、-、/)。.mode(EditMode.NUMERIC, true)— 同时开启数字模式和maskedEdit(第二个参数true)。没有maskedEdit,掩码不会被应用。顺序很重要:请一起调用mask(...)和mode(...)。TextField.getText()— 返回带掩码的文本("123.456.789-00"),适合以格式化形式显示/保存。TextField.getTextWithoutMask()— 只返回9位置的数字("12345678900"),适合验证并发送到后端。
对于日期,优先使用
setMode(EditMode.DATE, true):它会根据 locale 自动推导掩码(LocaleFormats.dateSeparator和LocaleFormats.dateFormat,例如dd/MM/yyyy或yyyy-MM-dd),并且还会打开 DatePicker。参见配方日期和时间。
注意
mode(EditMode.NUMERIC, true)中的顺序:NUMERIC/NORMAL模式仅在掩码已定义时才会根据掩码重新计算maxLength。请先定义mask(...),或在同一条流式链中定义。
完整示例(复制、粘贴并运行)
package com.exemplo;
import dev.crossfly.ui.*;
import dev.crossfly.ui.layout.*;
import dev.crossfly.ui.style.*; // TextFieldStyle(在样式中配置)
/** 可执行的主界面。将 launcher 指向此类(classname)并运行:gradlew :lwjgl3:run */
public class MainWindow extends Window
{
@Override
public void onShow() throws Exception
{
super.onShow();
setLayout(new VerticalLayout());
// CPF:123.456.789-00
TextField cpf = new TextField("");
cpf.caption("CPF");
cpf.<TextFieldStyle>getStyle()
.mask("999.999.999-99".toCharArray())
.mode(EditMode.NUMERIC, true); // NUMERIC + maskedEdit
// CEP:12345-678
TextField cep = new TextField("");
cep.caption("CEP");
cep.<TextFieldStyle>getStyle()
.mask("99999-999".toCharArray())
.mode(EditMode.NUMERIC, true);
Label resultado = new Label("");
Button enviar = new Button("Enviar");
enviar.onAction(o ->
{
String cpfFormatado = cpf.getText(); // "123.456.789-00"
String cpfLimpo = cpf.getTextWithoutMask(); // "12345678900"
if (cpfLimpo.length() != 11)
{
Hint.show("CPF deve ter 11 dígitos", 2000);
return;
}
resultado.setText(cpfFormatado + " · CEP: " + cep.getText());
});
add(LAY_FILL, cpf);
add(LAY_FILL, cep);
add(LAY_AUTO, enviar);
add(LAY_FILL, resultado);
}
}
下面的片段只展示核心部分。要运行它,请将其放入上面的
MainWindow骨架中。
最小片段
import dev.crossfly.ui.*;
import dev.crossfly.ui.style.*;
import static dev.crossfly.ui.UIConstants.EditMode;
// CPF:123.456.789-00
TextField cpf = new TextField("");
cpf.caption("CPF");
cpf.<TextFieldStyle>getStyle()
.mask("999.999.999-99".toCharArray())
.mode(EditMode.NUMERIC, true); // NUMERIC + maskedEdit
// CEP:12345-678
TextField cep = new TextField("");
cep.caption("CEP");
cep.<TextFieldStyle>getStyle()
.mask("99999-999".toCharArray())
.mode(EditMode.NUMERIC, true);
Button enviar = new Button("Enviar");
enviar.onAction(o ->
{
String cpfFormatado = cpf.getText(); // "123.456.789-00"
String cpfLimpo = cpf.getTextWithoutMask(); // "12345678900"
// 校验 cpfLimpo.length() == 11 后提交
});
深入了解
这个页面有帮助吗?感谢你的反馈!