getText()方法在有文本时返回null

时间:2013-04-25 00:13:07

标签: java swing jtextfield numberformatexception

每当我在文本框中输入一个数字并获取文本并进行转换时,我会得到一个例外:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

以下是该类的代码:

数字生成器:

package Main;

public class Number_Generator {

    public int makeRandom(){
        int Rnumber = 1;
        Rnumber = 1 + (int)(Math.random()*20);
        return Rnumber;
    }



}

Oper_add:

package Main.Oper_classes;
import Main.Number_Generator;
import javax.swing.*;
import java.awt.*;
import Main.Oper_check.*;

public class Oper_add {

    Number_Generator gen = new Number_Generator();
    public JTextField textbox = new JTextField(2);
    //make random numbers
            public Integer Rnumber1 = gen.makeRandom();
            public Integer Rnumber2 = gen.makeRandom();


    public void main(){
        //set textbox to null
        this.textbox.setText(null);

        //import classes
        Add_Check check = new Add_Check();
        //convert to String
        String Rnumber1S = Rnumber1.toString();
        String Rnumber2S = Rnumber2.toString();

        //make GUI
        JFrame frame = new JFrame("Addition Test");
        JPanel panel = new JPanel();
        FlowLayout fl = new FlowLayout();
        panel.setLayout(fl);

        JLabel num1 = new JLabel(Rnumber1S);
        JLabel sign = new JLabel("+");
        JLabel num2 = new JLabel(Rnumber2S);
        JLabel equals = new JLabel("=");
        JButton confirm = new JButton("Check");

        //add action listener
        confirm.addActionListener(check);

        //add componets to window
        panel.add(num1);
        panel.add(sign);
        panel.add(num2);
        panel.add(equals);
        panel.add(textbox);
        panel.add(confirm);

        //set frame settings
        frame.setContentPane(panel);
        frame.setVisible(true);
        frame.pack();

    }

}

add_check:

package Main.Oper_check;
import java.awt.event.*;
import javax.swing.JOptionPane;
import Main.Oper_classes.*;


public class Add_Check implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        Oper_add add = new Oper_add();

        String textbox = add.textbox.getText().trim();
        Integer textboxC = Integer.parseInt(textbox);
        Integer total = add.Rnumber1 + add.Rnumber2;


    }

}

2 个答案:

答案 0 :(得分:2)

Oper_add add = new Oper_add();
String textbox = add.textbox.getText().trim();
Integer textNumber = Integer.parseInt(textbox);

您正在创建一个新的Oper_add,其中包含一个新的空文本框。您期望该文本框具有值,但它不会。它与您正在与之交互的任何文本框无关。

答案 1 :(得分:1)

文本框当前有一个空字符串(或者只是空格 - trim删除空格)。它没有null。例外是因为空字符串不是有效数字。您应该捕获异常,然后在JOptionPane中使用它:

try {
    Integer textNumber = Integer.parseInt(textbox);
     ...
} catch (NumberFormatException ex) {
    JOptionPane.showMessageDialog(this, ex.getMessage(), "Number Error", JOptionPane.ERROR_MESSAGE);
}