java - 如何从类似于 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;
}
如果有人知道更好的方法来完成这个输入和响应系统,那就太好了。
谢谢。
解决方案
不要让程序等待。这是一个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("");
推荐阅读
- node.js - 无法将异步操作结果保存在数组中
- julia - 如何在 Julia 中使用嵌套列表推导
- android - Jetpack Compose LazyColumn 滚动监听器
- java - java.sql.drivermanager 不接受使用公共 IP 的 mysql jdbc url,没有合适的驱动程序
- node.js - Node.JS + Puppeteer:browser.close 冻结进程
- python - 将 mapbox choropleth 与 python 中的附加层和标记相结合;尝试覆盖坐标标记
- ruby-on-rails - 在 Rails 中,如何为同一渲染中的每个模型/对象应用不同的序列化程序?
- java - 使用google translate api java时某些语言的编码问题
- flutter - ¿ 如何比较两个 StreamTransformer?
- java - 将所有“ImmutableMap/List”构建工作卸载到编译时?