【问题标题】:Adding a TextField to JOptionPane将 TextField 添加到 JOptionPane
【发布时间】:2016-01-19 19:37:12
【问题描述】:

我正在开发一个显示“Hello”并使用 JOptionPane 接受用户输入的简单程序。我想阅读用户输入并将其与显示的单词进行比较。例如,程序将显示“Hello”,用户必须在文本框中输入一个单词。如果他们键入“Hello”,则将打印“Correct”。如果他们不输入 Hello,则将打印“不正确”。为了读取用户输入并比较两个字符串,我需要做什么?

public static void main(String[] args){

    String resp = "Hello";

    JOptionPane.showInputDialog(null, resp);

    String input = ; //what should go here                              

    if (resp.compareTo(input) == 0) {
        JOptionPane.showMessageDialog(null, "Correct!");
        } else
        JOptionPane.showMessageDialog(null, "Incorrect");
        }
    }
}

【问题讨论】:

  • 我很确定 JOptionPane.showInputDialog 返回一个字符串,所以让它看起来像 String input = JOptionPane.showInputDialog(null, "Hello");
  • 另外,看看How to Make Dialogs
  • @3kings 嘿,谢谢你的帮助!它有效

标签: java string swing jtextfield joptionpane


【解决方案1】:
public static void main(String[] args)
{

String resp = "Hello";

String input = JOptionPane.showInputDialog(null, resp);                         

if (resp.compareTo(input) == 0)
    JOptionPane.showMessageDialog(null, "Correct!");
else
    JOptionPane.showMessageDialog(null, "Incorrect");
}

【讨论】:

  • Swing GUI 应该在 EDT 上创建和更新(所以我建议删除方法名称和左大括号!),否则,+1。 OP:如果它有助于解决问题,请accept the answer
  • 如果它有助于解决问题,请accept the answer!另外,请参考your profile 中链接的一些早期问题,看看哪些问题也可以通过接受答案来“最终确定”。
猜你喜欢
  • 2012-12-07
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多