gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:52:00 24 4
gpt4 key购买 nike

每当我在文本框中输入数字并获取文本并将其转换时,我都会遇到异常:

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;


}

}

最佳答案

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

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

关于java - getText() 方法有文本时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com