如何将掩码设置为SWT文本以仅允许十进制 [英] How to set a Mask to a SWT Text to only allow Decimals

查看:131
本文介绍了如何将掩码设置为SWT文本以仅允许十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是用户只能在文本上输入十进制数字,我不希望它允许输入文本:

What I want is that the user can only input decimal numbers on a Text, I don't want it to allow text input as:


  1. HELLO

  2. ABC.34

  3. 34.HEY

  4. 32.3333.123

  1. HELLO
  2. ABC.34
  3. 34.HEY
  4. 32.3333.123

我一直在尝试使用VerifyListener,但它只给了我插入的文本部分,所以我最终得到了我想要的文本在插入之前插入文本,尝试组合文本,但是当你删除一个键(退格键)时我遇到了问题,我最终得到了像234 [BACKSPACE] 455这样的字符串。

I have been trying using VerifyListener, but it only gives me the portion of the text that got inserted, so I end up having the text that I want to insert and the text before the insertion, tried also combining the text, but I got problems when you delete a key (backspace) and I end up having a String like 234[BACKSPACE]455.

有没有办法在Text上设置Mask或成功地将VerifyEvent与当前文本组合以获得新文本,然后再将其设置为Text?

Is there a way to set a Mask on a Text or successfully combine VerifyEvent with the current text to obtain the "new text" before setting it to the Text?

推荐答案

您必须在文本上添加监听器使用 SWT.Verify 。在此监听器中,您可以验证输入仅包含十进制数。

You will have to add a Listener on the Text using SWT.Verify. Within this Listener you can verify that the input contains only a decimal number.

以下内容仅允许插入小数字到文本字段中。它会在每次更改文本中的内容时检查值并拒绝它,如果它不是小数。
这将解决您的问题,因为在插入新文本之前执行 VerifyListener 。新文本必须通过侦听器才能被接受。

The following will only allow the insertion of decimals into the text field. It will check the value each time you change something in the text and reject it, if it's not a decimal. This will solve your problem, since the VerifyListener is executed BEFORE the new text is inserted. The new text has to pass the listener to be accepted.

public static void main(String[] args) {
    Display display = Display.getDefault();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final Text textField = new Text(shell, SWT.BORDER);

    textField.addVerifyListener(new VerifyListener() {

        @Override
        public void verifyText(VerifyEvent e) {

            Text text = (Text)e.getSource();

            // get old text and create new text by using the VerifyEvent.text
            final String oldS = text.getText();
            String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

            boolean isFloat = true;
            try
            {
                Float.parseFloat(newS);
            }
            catch(NumberFormatException ex)
            {
                isFloat = false;
            }

            System.out.println(newS);

            if(!isFloat)
                e.doit = false;
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
}

这篇关于如何将掩码设置为SWT文本以仅允许十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆