查找异常调用者并修改以显示值

Find Exception caller and modify to display a value

假设我有 3 个 TextFields - 用于用户输入值(当程序为 运行 时):

TextField input1 = new JTextField("00");
TextField input2 = new JTextField("00");
TextField input3 = new JTextField("00");

当用户输入值时,程序会将这些值存储为整数(用于稍后的操作):

public void actionPerformed(ActionEvent e) {

  String temp1 = input1.getText();
  String temp2 = input.getText();
  String temp3 = input3.getText();

  int num1=0, num2=0, num3=0;
  if(e.getSource() == storeButton){
      try{
          num1 = Integer.parseInt(tem1);
          num2 = Integer.parseInt(temp2);
          num3 = Integer.parseInt(temp3);
      } 
      catch(NumberFormatException ex){
          JOptionPane.showMessageDialog(null, "Input must be an integer from 0 to 50");
      }
  }
}

如上代码所示,当用户单击 storeButton 时,TextFields 中的值将作为整数解析为特定变量,并且如果任何 TextFields 包含除一个整数,将弹出一条消息。

问题:

调用异常时,如何清除(设置为“0”)不包含数字的TextField? 不得清除包含整数的文本字段。 我可以通过在解析为整数时对每个 TextFields 使用 trycatch 来做到这一点,但这意味着代码重复太多(尤其是当有很多 TextField)。

看看 Character.isDigit()。您可以制作一个循环遍历每个字符串并检查它是否为数字的子方法。 或者,您可以在字符串上使用正则表达式来检查它是否是数字。 这使您可以摆脱 try/catch 并使用 if/else.

处理它们