将文本字段中的输入转换为 intigers javaFx

converting input in textfield to intigers javaFx

因此,我尝试使用 try 和 catch 方法从 textField 转换输入,但即使我输入了一个可以转换的值,我的代码也总是会抛出异常。

    public int enterButton() throws Exception {
        inputLocation.setText("your location is: " + inputLocation.getText());
        
        int location = 49;
        String input = inputLocation.getText();
        try {
            location = Integer.parseInt(input);
            inputLocation.setText("your location is: " + location);
            
        } catch (NumberFormatException ex) {
            inputLocation.setText("Not a valid location!");
            error.setText("setting location as 49");
        }
        
        return location;
    }

可能是什么问题?

public int enterButton() throws Exception {
  inputLocation.setText("your location is: " + inputLocation.getText()); // <---
        
  String input = inputLocation.getText();
  try {
    location = Integer.parseInt(input);
  } catch (NumberFormatException ex) {
    ...
  }
  return location;
}

此逻辑将始终使内容无法解析。

如果location的内容是123,标记的行会替换为your location is: 123。之后,您将该字符串放入 input 并且它将永远不会解析,因为它包含字符 your location is:.

不要这样做 -- 在字段前面使用标签,或更新不同的字段。或者至少,在获取文本并尝试解析它之前不要更新该字段。