0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dani
  • 57
  • 10
  • See this, it may help [enter link description here](https://stackoverflow.com/questions/15703644/how-to-filter-certain-characters-in-jtextfield) – Simo Apr 18 '17 at 13:29
  • *"a filed in whic the user write the price of a products."* `new JSpinner(new SpinnerNumberModel(0.0, 0.0, 999.99, .01));` – Andrew Thompson Apr 18 '17 at 19:45

4 Answers4

4

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();
        }
Dani
  • 57
  • 10
2

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • thanks, very helpful. But right now i have to use jtextfield because i've already created a mini program where i added lot of jtextfield – Dani Apr 19 '17 at 13:13
  • @Dani, 1) a JFormatedTextField is a JTextField. 2) A DocumentFilter can be used on a JTextField. 3) your current design is irrelevant. It doesn't work so you need to make changes anyway. Do things properly and don't take shortcuts. As you can see you have problems when you do things the wrong way. – camickr Apr 19 '17 at 14:33
0

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  
            }  
  • 1
    Can you add some explanation to this code only answer; [How to answer](https://stackoverflow.com/help/how-to-answer) goes into details on improving answers. – Akin Okegbile Aug 17 '20 at 13:47
0

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!!

Chivorn
  • 2,203
  • 2
  • 21
  • 37