Domanda

I have a DocumentListener that allows for a JTextFieldto represent the total of 7 other JTextFields. It adds and displays everything fine with just one exception; if fields that make up the total are populated and then removed, the total field still displays "0.00" when I would like it to just be blank. I tried playing around with different conditions but didn't have much luck so below is the code that I know works except for why I am here:

public class OvertimeSumListener implements DocumentListener {
private JTextField[] timeFields;
private JTextField total;

public OvertimeSumListener(JTextField[] timeFields, JTextField total) {
    this.timeFields = timeFields;
    this.total = total;
}

public void calculateTotal() {
    double sum = 0;
    for (JTextField timeField : timeFields) {
        String text = timeField.getText();
        try {
            sum += Double.parseDouble(text);
        } catch (NumberFormatException e) {
            // not a number - ignore
        }
    }
    total.setText(String.format("%.2f", sum));
}

public void insertUpdate(DocumentEvent e) {
    calculateTotal();
}

public void removeUpdate(DocumentEvent e) {
    calculateTotal();
}

public void changedUpdate(DocumentEvent e) {
    calculateTotal();
}

}

È stato utile?

Soluzione

Wouldn't this work:

if (sum > 0.0) {
    total.setText(String.format("%.2f", sum));
else {
    total.setText("");
}

Altri suggerimenti

In your method, try using the following:

for (JTextField timeField : timeFields) {
        String text = timeField.getText();
        try {
            sum += Double.parseDouble(text);
        } catch (NumberFormatException e) {
            // not a number - ignore
        }
}
if(sum>0.0) total.setText(String.format("%.2f", sum));
else total.setText("");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top