首页 > 解决方案 > 如何从类似于 Scanner.next() 的 JTextField 获取输入?

问题描述

我一直在试图弄清楚如何通过在JTextField. 我希望它类似于Scanner.next()接收输入的方式 - 程序“等待”直到给出输入,它被适当地存储以供进一步使用。我希望能够做到这一点,因为我的程序要求用户输入然后显示相应的文本。快速示例:

  • 程序:“你叫什么名字?”
  • 用户:(输入名称并按回车键)
  • 程序:“欢迎,(用户输入)。”

我可以从按下按钮中提取 JTextField 的内容,但我不知道如何让程序“等待”输入(“等待”直到按下输入)。

public static String getStringInput(String prompt)
{
    console.append(prompt);

    String input;

    //Here I need to get the input from a JTextField after I've pressed 
    //enter.

    return input;
}

如果有人知道更好的方法来完成这个输入和响应系统,那就太好了。

谢谢。

标签: javaswingactionlistenerjtextfield

解决方案


不要让程序等待。这是一个JFrame应用程序,不是命令行工具,所以在开发涉及窗口的东西时,不要抱着写命令行工具的心态。想象一下如果程序刚刚停止并在行后等待会发生什么String input;。窗口将冻结并且事件不会被处理,这是一个非常糟糕的用户体验。

我建议您在事件处理程序中为按钮单击执行所有操作。

// at class level
String[] prompts = new String[] { "prompt1", "prompt2", "prompt3" };
int currentPrompt = 0;

// inside the event handler
String text = textfield.getText();
switch (currentPrompt) {
    case 0:
        // text contains the input for prompt1
    case 1:
        // text contains the input for prompt2
    case 2:
        // text contains the input for prompt3
}

在 switch 案例中,您可以通过以下方式进入下一个提示:

currentPrompt++; // or set it equal to some other number if you wan to jump around
promptLabel.setText(prompts[currentPrompt]);
textField.setText("");

推荐阅读