为什么java不从GUI中获取数字?

时间:2013-06-02 14:17:26

标签: java swing jtextfield parseint

我创建了一个贷款计算器。但它没有计算价值。你能不能帮我找一下出错的地方。

import java.awt.*;
import javax.swing.*;



public void initUIPanel() {
    jf = new JFrame();
    jf.setTitle("Mortgage Calculator");
    jf.setLocation(100, 200);
    jf.setSize(530, 740);
    jf.setVisible(true);
    jf.setResizable(false);


    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
    JPanel pane = new JPanel(gbl);
    JPanel pane1 = new JPanel(gbl);
    JPanel pane2 = new JPanel(gbl);
    gbc.anchor = GridBagConstraints.WEST;



    gbc.weightx = 1.0;
    gbc.insets = new Insets(30, 3, 3, 3);
    loanAmount = new JTextField(12);
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;
    gbl.setConstraints(loanAmount, gbc);
    pane.add(loanAmount);



    loanTerm = new JTextField(15);
    gbc.weightx = 1.0;
    gbc.insets = new Insets(20, 3, 3, 3);
    loanAmount = new JTextField(12);
    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.BOTH;
    gbl.setConstraints(loanAmount, gbc);
    pane.add(loanAmount);




    gbc.insets = new Insets(30, 0, 3, 0);
    interestRate = new JTextField(4);
    gbc.gridx++;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.BOTH;
    gbl.setConstraints(interestRate, gbc);
    pane2.add(interestRate);


    b1 = new JButton("Calculate");
    b1.setPreferredSize(new Dimension(5, 25));
    gbc.gridx = 0;
    gbc.gridy = 5;
    gbc.insets = new Insets(20, 30, 0, 30);
    b1.addActionListener(this);
    gbl.setConstraints(b1, gbc);
    pane2.add(b1);




    jf.add(pane, BorderLayout.NORTH);
    jf.add(pane2, BorderLayout.SOUTH);
    jf.setVisible(true);
    jf.pack();


}

public void actionPerformed(ActionEvent e) {


    double amt, rate, pay;
    int time;
    String name;

    if (e.getSource() == b1) {
        amt = Double.parseDouble(loanAmount.getText());
        rate = Double.parseDouble(interestRate.getText());
        time = Integer.parseInt(loanTerm.getText());


        System.out.println(amt);
        System.out.println(rate);
        System.out.println(time);


    } else {
        jf.dispose();
    }
}




public static void main(String[] args) {
    // TODO Auto-generated method stub
    MortgageCalculator mc = new MortgageCalculator();
    mc.initUIPanel();



}

}

我有

的不同课程

我有不同的计算类,但它至少在相同的类中没有取值。当我输入任何值时,它会显示异常错误。 我编辑了代码,缩短了代码。我收到

的错误

线程中的异常" AWT-EventQueue-0" java.lang.NumberFormatException:对于输入字符串:"" 即使我把价值放在textAreas中。

1 个答案:

答案 0 :(得分:2)

您永远不会将JTextField loanTerm添加到JPanel pane,因此它保留默认的空String值。发生ActionListener时,空String会导致NumberFormatException

JTextField添加到容器中:

pane.add(loanTerm);