Search code examples
javaswingjtextfield

Convert lower to upper case using evt.consume() in JTextField


I created a method to validate a JTextField. When I am typing any alphabet character it should automatically convert into uppercase character, but I am not getting an uppercase.

How to solve this problem, when using evt.consume()?

Code snippet:

public void PRJ_TEXT_VALIDATION(JTextField PTxt, int PTxtLen, String POptnStr, KeyEvent Pevt){
               String TmpStr=PTxt.getText();
               char TmpChar=Pevt.getKeyChar();
               //TmpChar=Character.toUpperCase(TmpChar);
               if ((TmpStr.trim().length() + 1) <= PTxtLen){
                   if (POptnStr == "INTEGER") {
                      if (!((TmpChar>='0') && (TmpChar<='9'))){
                          Pevt.consume();
                      }
                   } else if (POptnStr == "NUMERIC"){
                          if(!((TmpChar>= '0' && TmpChar <= '9') || (TmpChar == '.'))){
                                Pevt.consume();
                          }
                  } else if (POptnStr == "ALPHABET"){
                         if(!(TmpChar>= 'a' && TmpChar <= 'z' || TmpChar >= 'A' && TmpChar <='Z')){
                             Pevt.consume();
                          }
                 } else if (POptnStr == "PHONE"){
                        if (!((TmpChar>= '0' && TmpChar <= '9') || (TmpChar == '-')||
                           (TmpChar == '+')||(TmpChar == '(')||(TmpChar == ')'))){
                            Pevt.consume();
                         }
                }
            }else{
                 Pevt.consume();
             }
         }

Solution

  • Use document filter to achieve this. You can find usage in DocumentFilter that maps lowercase letters to uppercase.