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



假设我有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来处理每个TextFields,但这意味着代码重复太多(特别是当有许多TextFields时)。

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

最新更新