2011年7月31日 星期日

[Java] 按下數字會出現在 TextField


//   最多輸入幾個數字

    int MAX_INPUT_LENGTH = 3;

    

                String getDisplayString (){

        return jTextField1.getText();

    }

                void setDisplayString(String s){

        jTextField1.setText(s);

    }

    

    

        void addDigitToDisplay(int digit){



//      紅色這個部份,一定要有不然程式會出錯

        String inputString = getDisplayString();

        

//                indexof 代表 0 在這個字串的第幾個

//               * http://www.java-samples.com/showtutorial.php?tutorialid=225

        if (inputString.indexOf("0") == 0){

            inputString = inputString.substring(1);

        }

//                 假如  (  (抓到字串不等於 0 或著輸入數字大於0)  和  輸入的字串總長 小於 MAX_INPUT_LENGTH )

        if ((!inputString.equals("0") || digit > 0)  && inputString.length() < MAX_INPUT_LENGTH){

            setDisplayString(inputString + digit);

        }

        





    }

        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        // TODO add your handling code here:



                addDigitToDisplay(1);



    } 

0 意見:

張貼留言