Question

In my project I'm putting a JTextField to set grand total in the invoice. Its name is txtGtotal. When the customer pays an advance he type its value in txtAdvance JTextField, and I wrote a cord to txtAdvance's keyreleasing to set the due payment to txtDue JTextField. (If customer didn't pay any advance he should type as 0 in txtAdvance and txtDue also set 0)

Given below is my cord to key event.

private void txtAdvanceKeyReleased(java.awt.event.KeyEvent evt) {
    double gtotal = Double.parseDouble(txtGtotal.getText());
    double ad = Double.parseDouble(txtAdvance.getText());
    double due = gtotal - ad;
}

My question is when I'm clearing the number value in txtAdvance and try to type another number value before typing I'm getting this java.lang.NumberFormatException: empty String error. But after I replaced that empty txtAdvance jtextfeild with a number value, system is wording properly. How can I stop that error. As they showing error is in second line of the cord. which make a variable called double ad.

Was it helpful?

Solution

How about the obvious solution:

private void txtAdvanceKeyReleased(java.awt.event.KeyEvent evt) {
    double gtotal = parseDouble(txtGtotal.getText());
    double ad = parseDouble(txtAdvance.getText());
    double due = gtotal - ad;
}

private double parseDouble(String s){
    if(s == null || s.isEmpty()) 
        return 0.0;
    else
        return Double.parseDouble(s);
}

OTHER TIPS

to get rid of the empty String error you can do a simple check.

   private void txtAdvanceKeyReleased(java.awt.event.KeyEvent evt) {
      if(!txtGtotal.getText().trim().equals("") && !txtAdvance.getText().trim().equals("")){
        double gtotal = Double.parseDouble(txtGtotal.getText());
        double ad = Double.parseDouble(txtAdvance.getText());
        double due = gtotal - ad;
      }
    }

You can say, that the action should not be fired on pressing Backspace, try this:

if(evt.getKeyCode() != 8){ //Backspace
    double gtotal = Double.parseDouble(txtGtotal.getText());
    double ad = Double.parseDouble(txtAdvance.getText());
    double due = gtotal - ad;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top