使用jTextField捕获异常

时间:2013-07-22 19:04:44

标签: java swing actionlistener jtextfield

我正在构建的系统计算英尺到英寸,但是每当其中一个文本字段打开时,系统就无法运行(例如(?? / 12)+?)我想知道如何在文本字段设置时设置它左边的数字默认设置为零。

package calcu;
import java.awt.event.ItemEvent;
import java.text.NumberFormat;
import java.awt.event.KeyEvent;
import javax.swing.JFormattedTextField.*;
import javax.swing.*;
import javax.swing.JFormattedTextField.*;

void carefull() {
    String sumthing = "";
    double feet = Double.parseDouble(jTextField1.getText());

    double inches = Double.parseDouble(jTextField2.getText());
    NumberFormat changer = NumberFormat.getNumberInstance();
    double tik = feet * 12;

    double tok = inches + tik;

    try {
        if (jTextField1.getText().trim().equals("")) {
            double ans = inches;
            sumthing = changer.format(ans);
        }
        if (jComboBox1.getSelectedItem().equals(" ")) {
            sumthing = changer.format(tok);
        }
    } catch (NumberFormatException e) {
        spum1.setText(sumthing);
    }
}  

2 个答案:

答案 0 :(得分:1)

你应该像这样抓住NumberFormatException

double feet;
try {
    feet = Double.parseDouble(jTextField1.getText());
} catch (NumberFormatException e) {
    feet = 0;
}
double inches;
try {
    inches = Double.parseDouble(jTextField2.getText());
} catch (NumberFormatException e) {
    inches = 0;
}

这也会将123kjh之类的非数字解释为0。

答案 1 :(得分:1)

你可以试试这个:

String stringFeet = jTextField1.getText();
double feet = stringFeet.isEmpty() ? 0d : Double.parseDouble(stringFeet);