简体   繁体   中英

JTextField accept only numbers and one dot

I want that my text field accept only numbers (digit) and one dot, because it is a field in which the user can write the price of products. I have this code but it doesn't work well, it only accept numbers and delete.

char c=evt.getKeyChar();
if(!(Character.isDigit(c))||(c==KeyEvent.VK_BACK_SPACE)||(c==KeyEvent.VK_DELETE)){
    getToolkit().beep();
    evt.consume();
}

Can someone help me to fix it?

I found a solution for this problem: this is the code i wrote

 char c=evt.getKeyChar(); if((Character.isDigit(c))||(c==KeyEvent.VK_PERIOD)||(c==KeyEvent.VK_BACK_SPACE)){ int punto=0; if(c==KeyEvent.VK_PERIOD){ String s=pricefield.getText(); int dot=s.indexOf('.'); punto=dot; if(dot!=-1){ getToolkit().beep(); evt.consume(); } } } else{ getToolkit().beep(); evt.consume(); }

Don't use a KeyListener. That is old code when using AWT.

Swing has newer and better API's.

The easiest way is to use a JFormattedTextField . Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and working examples.

The other option is so use a DocumentFilter . Read the section from the Swing tutorial on Implementing a DocumentFilter .

private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {

Get the keyTyped and pass it to the method validate.

        if(!validate(evt.getKeyChar())){

Char or keytyped is not a valid input, so let it consumed.

            evt.consume();
        }

this limit the input of Decimal, only ONE decimal point can be entered;

        if(evt.getKeyChar()==KeyEvent.VK_DECIMAL || evt.getKeyChar()==KeyEvent.VK_PERIOD){
            

get the whole string entered in the textField;

            String field = textField.getText();

get index of dot(. or decimal/period). indexOf() method returns -1 if String does not have any dot or decimal poits.

            int index = field.indexOf(".");


            if(!(index==-1)){ //index is not equal to -1
                evt.consume(); //consume
            }
          
        }
    }  

Every keypress, this method gets called.

private boolean validate(char ch){

this determine if the character has matching value to Integer, Decimal point, backspace or delete. It returns true if the char is a integer, decimal, delete or backspace, otherwise false. However it does not limit how many decimal points can be entered.

            if(!(Character.isDigit(ch)
                    || ch==KeyEvent.VK_BACKSPACE 
                    || ch==KeyEvent.VK_DELETE 
                    || ch==KeyEvent.VK_DECIMAL
                    || ch==KeyEvent.VK_PERIOD)){
                return false;
            }
        
            return true;
            }     

here is the whole code, I have provided some comments, hope these will help.

private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {                               

        if(!validate(evt.getKeyChar())){ //get char or keytyped
            evt.consume();
        }
        //limit one dot or decimal point can be entered
        if(evt.getKeyChar()==KeyEvent.VK_DECIMAL || evt.getKeyChar()==KeyEvent.VK_PERIOD){
            
            String field = textField.getText(); //get the string in textField
            int index = field.indexOf("."); //find the index of dot(.) or decimal point
            if(!(index==-1)){ //if there is any
                evt.consume(); //consume the keytyped. this prevents the keytyped from appearing on the textfield;
            }
          
        }
    }     
    //determine if keytyped is a valid input
     private boolean validate(char ch){
        
            if(!(Character.isDigit(ch)
                    || ch==KeyEvent.VK_BACKSPACE 
                    || ch==KeyEvent.VK_DELETE  
                    || ch==KeyEvent.VK_DECIMAL 
                    || ch==KeyEvent.VK_PERIOD 
                    )){

                return false; //return false, because char is invalid           
            }
        
            return true; // return true, when the if statement above does not meet its conditions  
            }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM