开发者

how to make a Text prevent the inputs more than 'x' number of digits?

My question is:

I want the Text field in Eclipse RCP to allow only the digits to be keyed in as inputs and the requirement is that it should allow only up to 'x' (let's say x=5) characters.

How can I accomplish it in RCP ?

I've tried the code like:

txtInput.addListener(SWT.Verify, new DecimalText(
       开发者_如何学JAVA         txtInsuranceValue, 8, 1000.00));

where txtInputis a Text field. But this listener failed when I made repeated input into this field at run time.

Any alternatives please ?


This will set the maximum number of characters in your Text control to five and allow only digits to be entered:

    txtInput.setTextLimit(5);

    txtInput.addVerifyListener(new VerifyListener() {
        public void verifyText(VerifyEvent event) {
            // Assume we allow it
            event.doit = true;

            String text = event.text;
            char[] chars = text.toCharArray();

            //Don't allow if text contains non-digit characters
            for (int i = 0; i < chars.length; i++) {
                if (!Character.isDigit(chars[i])) {
                    event.doit = false;
                    break;
                }
            }
        }
    });

EDIT: I've modified my answer to allow a user to also set text with "setText(String string)" while still disallowing non-digit characters.


In general, solutions like adding verifyListeners/focusListeners are not complete and won't work with all situations. For example, what happens when the user copy-pastes some text into this text box?

If all you want is to get numerical inputs from the user, you should be using Spinner widget instead of Text widget. You could easily set the minimum and maximum limits on the Spinner.

See the snippets for more usage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜