JTextField t1 = new JTextField(" ");
String a = t1.getText();
int intA = Integer.parseInt(a);
System.out.println(intA);
Error
java.lang.NumberFormatException: For input string: "1 "
附上我的代码
public class Testing extends JPanel {
public int s;
public Testing() {
JPanel p = new JPanel();
JTextField t1 = new JTextField(" ");
JTextField t2 = new JTextField(" ");
JTextField t3 = new JTextField(" ");
JButton b3 = new JButton("result");
p.add(t1);
p.add(t2);
p.add(t3);
p.add(b3);
add(p);
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String a = t1.getText();
int intA = Integer.parseInt(a);
System.out.println(intA);
// String b = t2.getText();
//t3.setText(a+"");
} catch (NumberFormatException ignored) {
System.out.println(ignored);
}
}
});
}
public static void main(String... arg) {
Testing p = new Testing();
JFrame frame = new JFrame();
frame.add(p);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
//导包。
import javax.swing.*;
import java.awt.event.*;
class JTextFieldDemo
{
}
综上所述:
楼主出现如上问题是因为jtf.getText();方法应该在输入内容后才让它执行,而楼主所示的代码却让它在运行时就执行,所以会报错。(个人拙见,嘿嘿)
谢谢@Sjs_k 的答案
把
JTextField t1 = new JTextField("");
改去JTextField t1 = new JTextField(5);
就行了