我已经浏览了整个互联网,无法找到我为什么会发生这种情况。 基本上我正在尝试创建一个TextField,它创建一个数字字符串,并将该字符串转换为整数,并将标签更改为数字+1 每当我尝试使用Integer.parseInt它崩溃
这是我的代码
public class dfadsfa {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dfadsfa window = new dfadsfa();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public dfadsfa() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
String Text;
int Number = Integer.parseInt(Text); //This line Screws it up
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNumber = new JLabel("");
lblNumber.setBounds(198, 181, 61, 16);
frame.getContentPane().add(lblNumber);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Text = textField.getText();
lblNumber.setText(Number+1+"");
}
});
textField.setBounds(163, 140, 130, 26);
frame.getContentPane().add(textField);
textField.setColumns(10);
}
}
这是显示的消息 -
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at dfadsfa.<init>(dfadsfa.java:42)
at dfadsfa$1.run(dfadsfa.java:21)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
答案 0 :(得分:5)
您有一个未初始化的String文本。在尝试解析int时,这可以保证失败。
String Text;
int Number = Integer.parseInt(Text);
在尝试解析int之前,您应该初始化此text
。
答案 1 :(得分:0)
文本未初始化,因此它给出了NumberFormatException。 如果传递的字符串不包含可解析的整数,Integer.parseInt()方法将给出NumberFormatException。
使用
String Text = "0"
解决问题