【发布时间】:2023-03-19 18:28:01
【问题描述】:
我没有很多使用 KeyListeners 的经验,但我在我的应用程序中使用过它,它工作正常,只是我需要等待输入才能继续我的程序。为此,我做了一个 while 循环,循环直到 String temp 不为空(这意味着会有输入)。
问题是无法输入 JTextField(称为输入)。下面是我的两种方法的代码,它们应该一起工作,以便可以返回我的 JTextField(输入)中的文本(作为临时)。我不确定为什么这不起作用或如何解决它。
我的 KeyListener 的 keyPressed 方法:
public void keyPressed(KeyEvent e)
{
//only sends text if the enter key is pressed
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
//if there really is text
if (!input.getText().equals(""))
{
//String temp is changed from null to input
temp=input.getText();
//text sent to another JTextField
output.append(temp+"\n");
//input no longer has text
input.setText("");
}
}
}
试图获取文本的方法,也在我的 KeyListener 类中
public String getTemp()
{
booleans isNull=temp==null;
//loops until temp is not null
while (isNull)
{
//unnecessary line of code, only used so the loop not empty
isNull=checkTemp();
}
return temp;
}
public boolean checkTemp()
{
return temp==null;
}
【问题讨论】:
-
它正在使用swing
-
为什么不使用对话框来获取用户的输入?此外,您可以在输入字段上注册一个侦听器。
-
它基本上就像一个聊天机器人,所以我认为这会显着改变感觉,
-
摆脱所有这些代码,而是将 ActionListener 添加到 JTextField。
-
这就是 keyListener 已经存在的地方
标签: java swing while-loop keylistener