Search code examples
javajtextfieldkeyevent

JTextField limiting input after period


I'm writing a CashRegister program and I'm currently working on the CashierView where I have added an option for the Cashier to input the amount of cash received by the customer. I now formatted it so that the user only can input numbers and 1 period. I now want to limit the numbers you can input after the period to two. I'm struggling to make this work.

I commented out one of the codes that I tried, but didn't work, incase it might be interesting.

Appreciate all the help! Br, Victor

    private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {                                       
    char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
    //boolean tail = false;
    if ((Character.isDigit(c) || (c == KeyEvent.VK_BACKSPACE) || c == KeyEvent.VK_PERIOD)) {        
        int period = 0;  
        if (c == KeyEvent.VK_PERIOD) { //Allows only one period to be added to the textfield
            //tail = false;
            String s = getTextFieldCash();
            int dot = s.indexOf(".");
            period = dot;
            if (dot != -1) {
                evt.consume();
            }
        }
       //. if (tail=true){  //This is the code that I tried to use to limit  input after the period to two

           // String x = getTextFieldCashTail();
          //  if (x.length()>1){
             //   evt.consume();
         //   }
       // }
    } 
    else {
        evt.consume();
    }
}  

Solution

  • If you're dead set on doing this with a KeyEvent, here's one possible method:

    private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
        char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
        if ((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_PERIOD)) {
            String s = getTextFieldCash();
            int dot = s.indexOf(".");
            if(dot != -1 && c == KeyEvent.VK_PERIOD) {
                evt.consume();
            } else if(dot != -1 && c != KeyEvent.VK_BACK_SPACE){
                String afterDecimal = s.substring(dot + 1);
                if (afterDecimal.length() > 2) {
                    evt.consume();
                }
            }
        }
    }
    

    Hope this helps. Just keep in mind that by listening to a KeyEvent, if someone copies and pastes values into your JTextField, this won't catch that. If you want to catch any possible type of input, you'll want to use a DocumentListener. If you're wondering how to use a DocumentListener, here is some code that shows how to use it on a JTextField.