JOptionPane和扫描仪输入问题 [英] JOptionPane and Scanner input issue

查看:52
本文介绍了JOptionPane和扫描仪输入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,其中我需要使用JOptionPane在窗口上打印字符串.该行的代码如下所示:

I'm writing a program where at one point, I need to print a String on a window using JOptionPane. The code for the line looks something like this:

JOptionPane.showMessageDialog(null, "Name: " + a.getName());

getName函数引用我创建的对象a,该对象具有一种返回String的方法.但是,当我的代码到达这一点时,该程序似乎进入了某种无限循环,因为该窗口永不弹出,而在使用调试时,它似乎永无止境.

The getName function refers to the object a that i created that has a method that returns a String. However, when my code reaches this point, the program appears to enter some kind of infinite loop as the window never pops up and when using debug, it appears never-ending.

主要是,当我使用getName时,我允许用户在主驱动程序中使用其他函数来设置此名称.

The main thing is, when I use getName, I am allowing the user the set this name with a different function earlier in the main driver.

getName()基本上是一行,返回名称;

getName() is basically one line, return name;

setName()函数的代码基本上是:

The code for my setName() function is basically:

Scanner a = new Scanner(System.in);
System.out.print("Pick a name: ");
name = in.nextLine();
a.close();

Name是类中的一个私有变量. close()不是必需的,但是我尝试了一下以查看它是否有效果.

Name is a private variable in the class. The close() isn't necessary but I tried it to see if it had any effect.

我注意到的是,如果使用上面的代码,则窗口永远不会弹出,并且陷入无限循环.但是,如果我只是将name = line更改为任何内容,例如:

What I did notice is that, if I use the above code, the window never pops up, and I get stuck in an infinite loop. However, if I simply change the name = line to anything, such as:

name = "foo";

代码运行平稳,窗口弹出,而且我不会陷入循环中.即使在程序提示时我没有输入名称(导致字符串为空),窗口也不会弹出.谁能帮助我并建议我为什么发生这种情况?谢谢.

The code runs smoothly, the window pops up, and I do not get stuck in a loop. Even if I do not input a name when the program prompts me to, resulting in a null String, the window still doesn't pop up. Can anyone help and advise me on why this is happening? Thanks.

推荐答案

使用Scanner操作在JOptionPane使用的WaitDispatchSuport类中创建一个块,该块检查非调度线程是否阻塞了IO.调用Scanner.close()不会解除对线程的阻塞.

Using Scanner operations creates a block in the WaitDispatchSuport class used by JOptionPane which checks non-dispatch threads are free from blocking IO. Calling Scanner.close() will not un-block the thread.

一种解决方案是从 EDT showMessageDialog :

One solution is to call showMessageDialog from the EDT :

Scanner a = new Scanner(System.in);
System.out.print("Pick a name: ");
final String name = a.nextLine();

SwingUtilities.invokeLater(new Runnable() {

   @Override
   public void run() {
      JOptionPane.showMessageDialog(null, "Name: " + name);             
   }
});

这篇关于JOptionPane和扫描仪输入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆