在用户输入之前检查空的JTextField

时间:2015-04-04 10:10:25

标签: java swing jpanel jtextfield

private class CalculateButtonHandler implements ActionListener{

    public CalculateButtonHandler(JTextField initialAmmount, JTextField yearsToMaturity, JTextField interestRate){
        double endingBalance;
        String text = interestRate.getText();
        int interestRateInt = Integer.parseInt(text);

        String text1 = yearsToMaturity.getText();
        int yearsToMaturityInt = Integer.parseInt(text);

        String text2 = initialAmount.getText();
        int initialAmountInt = Integer.parseInt(text);

        endingBalance = initialAmountInt * Math.pow((1 + interestRateInt/1), 1 *           yearsToMaturityInt);
    }

    public void actionPerformed(ActionEvent e){
    }
}

当前运行时错误: 线程" main"中的例外情况java.lang.NumberFormatException:对于输入字符串:""

我假设发生运行时错误,因为程序运行时没有输入,并且用户没有机会输入要解析为int的字符串。我无法弄清楚如何检查这一点。

1 个答案:

答案 0 :(得分:0)

处理按钮单击事件的代码需要在actionPerformed方法中,而不是在构造函数中。

private class CalculateButtonHandler implements ActionListener{

    private final JTextField interestRate;
    private final JTextField yearsToMaturity;
    private final JTextField interestRate;

    public CalculateButtonHandler(JTextField initialAmmount, JTextField     yearsToMaturity, JTextField interestRate) {
        this.initialAmmount = initialAmmount;
        this.yearsToMaturity = yearsToMaturity;
        this.interestRate = interestRate;
    }

    public void actionPerformed(ActionEvent e){
       double endingBalance;
       String text = interestRate.getText();
       int interestRateInt = Integer.parseInt(text);

       String text1 = yearsToMaturity.getText();
       int yearsToMaturityInt = Integer.parseInt(text);

       String text2 = initialAmount.getText();
       int initialAmountInt = Integer.parseInt(text);

       endingBalance = initialAmountInt * Math.pow((1 + interestRateInt/1), 1 *           yearsToMaturityInt);
   }
}