about event handling

Help
wason
2006-10-04
2013-05-23
  • wason
    wason
    2006-10-04

    a BTextField.just allow user to enter numbers.so I add KeyPressedEvent listener.i want to ignore all letter which is not a number entered by user.but KeyPressedEvent pass to my listener,then still pass to the swing default handler.how can i change it only handled by my own listener?not pass to the swing default handler.

     
    • wason
      wason
      2006-10-04

      I solved it by:
      void onValueChanged(ValueChangedEvent event)
      {
        int length = _telTextField.getLength();
        if(length>TEL_LENGTH)//assure length.
        {
          _telTextField.setText(_telTextField
            .getText().substring(0, TEL_LENGTH));
          return;
        }else if(length>0)//ensure it is a number.
        {
          tring last = _telTextField.getText()
            .substring(_telTextField.getLength()-1);
          try
          {
            Integer.parseInt(last);
          }catch(NumberFormatException e)
          {
           _telTextField.setText(_telTextField.getText()
             .substring(0,_telTextField.getLength()-1));
          }
        }
      }

       
    • Peter Eastman
      Peter Eastman
      2006-10-05

      You're assuming that if there's an invalid character, it's the very last one.  That's fine if they're typing at the end of the text field, but if they hit the left arrow a few times and type a letter into the middle of the text, you won't handle it correctly.

      A better solution: scan through every character in the string, check each one to see if it's a digit, and if so, remove it.

      Peter

       
    • wason
      wason
      2006-10-05

      yeah,you are right.thank you for your help.we may need a verifation framework to make application clearer.like TextField only can enter numbers and so on is very common.Do you have any solution to do them more easier and clearer?

       
    • Peter Eastman
      Peter Eastman
      2006-10-07

      If this is something you'll be using a lot, create a BTextField subclass that encapsulates it.  Then it's easy to use wherever you want it.

      Swing has JFormattedTextField, which is basically a framework for creating specialized text fields like this.  I've never found it very useful - it requires much more work to use than the solution described above - which is why I haven't created a Buoy version of it.  Another option is to create a Document implementation (subclass PlainDocument) that rejects all non-numeric characters.  That's probably the "most correct" solution in some sense, but again, it's much more work.

      Peter