每当我在文本框中输入数字并获取文本并将其转换时,我都会遇到异常:
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;
}
}
操作添加:
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();
}
}
添加检查:
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;
}
}