【发布时间】:2018-04-20 08:42:23
【问题描述】:
我是 Java 新手。我正在尝试从 JavaFX 中的计算器的文本字段中获取一个 int。我有 2 个文本字段,人们可以在其中写一个数字:
hb.getChildren().addAll(label1, textField);
textField.getText();
hb.setSpacing(10);
hb.getChildren().addAll(label2, textField2);
textField2.getText();
hb.setSpacing(10);
所以这是我从文本字段中获取 int 的方法,但它不起作用:
int x = Integer.parseInt(textField.getText());
int y = Integer.parseInt(textField2.getText());
有谁知道我做错了什么?我在互联网上看到人们使用事件,但我不确定在这种情况下我是否必须使用它。
错误日志:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at test.start(test.java:57)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
... 1 more Exception running application test
希望有人能帮帮我,
托马斯
【问题讨论】:
-
你遇到了什么错误?
-
解释“它不起作用”部分。不需要在第一部分调用
textField.getText();。 -
您需要将
int y = Integer.parseInt(textField2.getText());放在按钮操作中。如果您在无法确定用户是否能够输入内容之前调用它 -
为什么在第一个区块中调用
textField.getText();?这应该怎么做? -
你应该看更多的教程或者买一本像 Head First Java 这样的书。因为您的代码没有正确的意义。同时发布错误日志。我不卖 Head First Java。
标签: java javafx calculator