我在计算机编程学习,我试图模拟一台ATM机。我在textfeild上有一些名称为inputArea的问题。这是我的一些代码
这是GUI的构造函数
public ATM() {
inputArea = new JTextField();
inputArea.setText("");
inputArea.setEditable(true);
add( inputArea, BorderLayout.SOUTH);
TextFieldHandler handler = new TextFieldHandler();
inputArea.addActionListener(handler);
}
这是事件处理程序
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
if(event.getSource()==inputArea) {
inputMessage = event.getActionCommand();
inputArea.setText("");
}
}
}
程序启动时会崩溃。如何让它停止并等到我将值输入文本字段然后按回车键。所以accountNumber可以成为我输入的值。
private void authenticateUser()
{
displayMessage( "\nPlease enter your account number: " );
int accountNumber = Integer.parseInt(inputMessage);
displayMessage( "\nEnter your PIN: " ); // prompt for PIN
int pin = Integer.parseInt(inputMessage);
}
这是错误消息
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)
at java.base/java.lang.Integer.parseInt(Unknown Source)
at java.base/java.lang.Integer.parseInt(Unknown Source)
at ATM.authenticateUser(ATM.java:118)
at ATM.run(ATM.java:94)
at ATMCaseStudy.main(ATMCaseStudy.java:14)
如果有任何建议,请随时告诉我。非常感谢。
解析“”到Integer时遇到问题。我不使用Swing,但我有一些想法来解决它:1)尝试更改默认值,inputArea.setText("0");
2)尝试有效输入3)使用debbuger检查“inputMessage”中的值 - 如果你不'从不使用它,请检查它,在将来非常有用
看起来你有一个命令行程序和一个GUI程序的组合。
摆脱命令行功能。
你可以:
请查看上面有关How to Use Password Fields
和How to Use Buttons
的教程中的部分,以获取更多信息和简单的工作示例,以帮助您更好地使用GUI。