无法从Java GUI Textfield获取输入值

问题描述 投票:-2回答:2

我在计算机编程学习,我试图模拟一台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)

如果有任何建议,请随时告诉我。非常感谢。

java
2个回答
0
投票

解析“”到Integer时遇到问题。我不使用Swing,但我有一些想法来解决它:1)尝试更改默认值,inputArea.setText("0"); 2)尝试有效输入3)使用debbuger检查“inputMessage”中的值 - 如果你不'从不使用它,请检查它,在将来非常有用


0
投票

看起来你有一个命令行程序和一个GUI程序的组合。

摆脱命令行功能。

你可以:

  1. 显示JOptionPane以提示用户输入所需信息。您需要两个选项窗格,一个用于提示输入帐号,另一个用于提示。有关更多信息和工作示例,请阅读How to Make Dialogs上Swing教程中的部分。
  2. 创建自定义JDialog。 JDialog就像一个JFrame,您可以向对话框添加组件。因此,您需要为帐号添加标签和文本字段,然后为该针添加第二组标签和格式化文本字段。然后,您需要添加一个按钮来关闭对话框并从文本字段中读取数据,以便您可以进行处理。

请查看上面有关How to Use Password FieldsHow to Use Buttons的教程中的部分,以获取更多信息和简单的工作示例,以帮助您更好地使用GUI。

© www.soinside.com 2019 - 2024. All rights reserved.