Dani
Dani

Reputation: 57

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?

Upvotes: 0

Views: 2723

Answers (4)

Chivorn
Chivorn

Reputation: 2363

Bellow is my sample code that I already tested and working as expected. I also added beep sound when user input or press wrong key.

private void textFieldScoreKeyTyped(java.awt.event.KeyEvent evt) {                                        
       char c =  evt.getKeyChar();
       if(c == KeyEvent.VK_BACK_SPACE){
            evt.consume(); 
       }else if(Character.isLetter(c) || String.valueOf(c).trim().isEmpty()){
           getToolkit().beep();
           evt.consume(); 
       }else{
           try{
               Double.parseDouble(textFieldScore.getText()+c);
           }catch(NumberFormatException e){
               getToolkit().beep();
               evt.consume();
           }
       }
    }

Good luck everyone!!

Upvotes: 0

helloWorld
helloWorld

Reputation: 1

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  
            }  

Upvotes: 0

Dani
Dani

Reputation: 57

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();
        }

Upvotes: 4

camickr
camickr

Reputation: 324078

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.

Upvotes: 2

Related Questions