天天看點

swt中text隻能輸入數字的完美解決

搞java有兩年了,技術上一直也不怎麼樣,自己開發點東西,這個可是自己好不容易搞定的,希望能給後來人幫助

text.addVerifyListener(new VerifyListener() {

      public void verifyText(VerifyEvent event) {

       event.doit = false;

       char myChar = event.character;

       if(text.getText().indexOf(".")==-1){//沒有小數點時,可以輸入小數點。(因為此驗證是確定一次隻能輸入一個字元。)

        if (myChar=='0' || myChar=='1' || myChar=='2' || myChar=='3' || myChar=='4' || myChar=='5'|| myChar=='6' || myChar=='7' || myChar=='8' || myChar=='9' || myChar == '/b' ||myChar == '.') {

         event.doit = true;

        }

       }else{//隻要有小數點,就不能輸入小數點。

        if (myChar=='0' || myChar=='1' || myChar=='2' || myChar=='3' || myChar=='4' || myChar=='5'|| myChar=='6' || myChar=='7' || myChar=='8' || myChar=='9'  || myChar == '/b') {

         event.doit = true;

        }//小數點後夠兩位,輸入無效

        if(text.getText().substring(text.getText().indexOf(".")+1).length()>1){

          event.doit=false;

        }

       }//倒退有效

       if(myChar == '/b')

        event.doit=true;

      }

      }

     );