Search code examples
javajava-metextfieldmidp

How to filter keys in MIDP TextField?


I have a TextField.PhoneNumber but I would like to filter out "+" character. In other words, I need a new constraint for TextField. Is there a way to define a new constraint with TextField?

How about preventing keys from cycling on a mobile phone within a midp?


Solution

  • It might not what you really want. But, MIDP does not support change constraint rule as you want. So, I suggest HACK for your purpose.

    How about use ItemStateListener to check if text field contains string which you want to filter out and if this string is exist, change text field forcefully.

    The code could be looks like below:

    // set item state listener
    form.setItemStateListener(this);
    
    // check if text field contains invalid string
    // then replace it
    public void itemStateChanged(Item item) {
        if (item == getTextField()) {
            TextField t = (TextField)item;
            String s = t.getString();
            // + is invalid string
            int pos = s.indexOf("+");
            if (pos != -1) {
                t.setString(s.substring(0, pos) + s.substring(pos + 1));
            }
        }
    }