首页 \ 问答 \ 来自textfield的Java int(Java int from textfield)

来自textfield的Java int(Java int from textfield)

我是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

我希望有一个人可以帮助我,

托马斯


I'm new to Java. I'm trying to get an int from a textfield for my calculator in JavaFX. I have 2 textfields where people can write a number:

hb.getChildren().addAll(label1, textField);
textField.getText();
hb.setSpacing(10);
hb.getChildren().addAll(label2, textField2);
textField2.getText();
hb.setSpacing(10);

So this is what I made to get an int from a textfield but it doesnt work:

int x = Integer.parseInt(textField.getText());
int y = Integer.parseInt(textField2.getText());

Does anyone know what I'm doing wrong? I saw on internet people used event but I'm not sure if in this case I have to use it.

Error log:

 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

I hope someone can help me,

Thomas


原文:https://stackoverflow.com/questions/49937561
更新时间:2021-12-20 13:12

最满意答案

是的,这是一个非常基本的单身人士。 它做它应该做的事情,没有特别的装饰。

你在互联网上找到的例子通常描述一个懒惰的初始化单例,强调getInstance()的性能(即避免同步,不允许在多个线程同时调用getInstance()时创建多个实例)。

如果您不需要延迟初始化,那么创建单例变得非常简单,就像您在Runtime看到的一样。

最后,你可以找到很多关于单例模式的东西(其中一些是误导性的),但它并不真正保证它。 这并不是那么有趣,有些人认为它是一种反模式,如果你发现自己编写自己的单例很多,你可能做的不太对劲。

最后,如果你确实认为你需要一个懒惰的初始化单例,那么当前的标准实现是enum

public enum MySingleton {
    INSTANCE

    public String getSarcasticMessage() {
        return "I'm a lazy loaded singleton, use me for everything!";
    }
}

MySingleton.INSTANCE.getSarcasticMessage();  // This is how to use it

Yes, that's a very basic singleton. It does what it's supposed to do with no special frills.

The examples you find on the internet usually describe a lazy initialized singleton with emphasis on the performance of getInstance() (i.e. avoid synchronized, don't allow creating multiple instances if multiple threads call getInstance() at the same time and so forth).

If you don't need lazy initialization it becomes very simple to create a singleton, as you can see with Runtime.

Finally, you can find a lot of things written about the singleton pattern (some of them misleading), but it doesn't really warrant it. It's not that interesting, some consider it an anti-pattern, and if you find yourself writing your own singletons a lot, you're probably doing something not quite right.

Extra finally, if you do think you need a lazily initialized singleton, the current standard implementation is with enum.

public enum MySingleton {
    INSTANCE

    public String getSarcasticMessage() {
        return "I'm a lazy loaded singleton, use me for everything!";
    }
}

MySingleton.INSTANCE.getSarcasticMessage();  // This is how to use it

相关问答

更多
  • 选择单身优于静态类的一个很好的理由(假设你没有更好的模式可供使用)),就是将一个单例实例与另一个实例交换。 例如,如果我有这样的日志类: public static class Logger { public static void Log(string s) { ... } } public class Client { public void DoSomething() { Logger.Log("DoSomething called"); } } 它工作得很 ...
  • 不它不是。 你没有声明myClass private static final ,也没有声明getInstance()是static 。 该代码也没有真正编译。 这里是辛格尔顿的成语: public class MyClass { private static final MyClass myClass = new MyClass(); private MyClass() {} public static MyClass getInstance() { retur ...
  • 你是对的。 系统属性是静态的,所以为什么不为它们制作静态的持有者? 作为例子,而不是从每次我需要它们时从System.getProperty获取file.separator或line.sparator我可以像这样拥有它们: public class MyConstants { public static final String FILE_SEPARATOR = System.getProperty("file.separator"); public static final Str ...
  • 是的,这是一个非常基本的单身人士。 它做它应该做的事情,没有特别的装饰。 你在互联网上找到的例子通常描述一个懒惰的初始化单例,强调getInstance()的性能(即避免同步,不允许在多个线程同时调用getInstance()时创建多个实例)。 如果您不需要延迟初始化,那么创建单例变得非常简单,就像您在Runtime看到的一样。 最后,你可以找到很多关于单例模式的东西(其中一些是误导性的),但它并不真正保证它。 这并不是那么有趣,有些人认为它是一种反模式,如果你发现自己编写自己的单例很多,你可能做的不太对劲 ...
  • 在几乎所有情况下,单例的一点是你不关心谁首先实例化它。 谁是第一个打电话给[Something sharedSomething]的人就是创作者。 您希望使用“ 如何实现与ARC兼容的Objective-C单例 ”中给出的模式?它将确保单例只创建一次。 In almost all cases, the point of a singleton is you don't care who first instantiates it. Whoever is the first to call [Something ...
  • 这是很多人遇到单身人士的常见问题。 虽然我不能具体评论NHibernate,但请查看Misko的文章 ,了解为什么单例设计模式会遇到您描述的问题。 一定要阅读评论和链接文章,以了解如何处理它(或在谷歌搜索“哪里有所有单身人士?”)。 如果你对这个话题感兴趣,你可能也想谷歌“单身 - 我爱你 - 但是 - 你带来了我” 希望这有点帮助。 This is a common problem that many people encounter with Singletons. While I can't comm ...
  • 这是一个有效的单身人士课吗? 现在,编辑后的答案是肯定的,它是有效的,它也是线程安全的,因为所有非函数范围的静态变量都是在main()之前构造的,而只有一个活动线程。 C ++标准n3337第3.6.2 / 1节3.6.2 / 2:初始化非局部变量 有两大类命名的非局部变量:静态存储持续时间(3.7.1)和线程存储持续时间(3.7.2)。 作为程序启动的结果,具有静态存储持续时间的非局部变量被初始化。 具有线程存储持续时间的非本地变量将作为线程执行的结果进行初始化。 在每个启动阶段中,初始化如下进行。 静态 ...
  • 我不认为这种方法存在问题。 我经常使用单身人士,从来没有遇到任何问题。 您只需要记住android可能在需要内存时删除单例实例,因此每次获得单例实例时都需要检查null。 I don't think there is an issue with this approach. I use singletons quite often and never had any problems. You just need to keep in mind that android might remove the s ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)