【问题标题】:SWT: input validation: prevent input of sub and superscript numbersSWT:输入验证:防止输入下标和上标数字
【发布时间】:2015-01-29 10:38:56
【问题描述】:

我正在验证来自 swt 文本小部件的输入,但我未能阻止输入子和上标数字。我的目标是只允许数字输入。我正在使用 SWT 验证侦听器,我的代码是这样的:

[...]
Text input = new Text (parent, SWT.CENTER);
input.addListener(SWT.VERIFY, new Listener(){
public void handleEvent(Event e){
    if ( (e.character >= '0' && e.character <= '9') || e.character == SWT.BS || e.character == SWT.DEL){
        e.doit = true;
    } else {
        e.doit = false;
    }
}
});
[...]

我曾尝试使用类似的方法手动过滤它,但这并没有起到作用:

private boolean isSup(character c){
    if (c == '^0'){
        return true;
    } else if(c == '^1'){
        return true;
    } [...] else {
        return false;
    }
}

可能有一种简单直接的方法可以做到这一点,但我没有看到它,谷歌也没有提供答案。

有人知道如何实现吗?

【问题讨论】:

  • 你问的是这个Unicode上标和下标数字吗(比如U+2080代表下标0)?

标签: java validation input swt


【解决方案1】:

与此同时,我找到了适合我的解决方案;我把它贴在这里,希望它可以帮助别人。

input = new Text(parent, style);    
input.addVerifyListener(new VerifyListener(){
        e.doit = false;
        String DIGIT = "[0-9]*";
        if (e.text.matches(DIGIT)){
            e.doit = true;
        }
    });

此解决方案确实允许使用前导零,但这些对我而言不是问题。我不知道,为什么在算术上比较字符不起作用,但 e.text 及其匹配方法工作得很好。

【讨论】:

    猜你喜欢
    • 2022-11-08
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多