用于从 JTextField 获取文本的键绑定



我有一个JTextField,它将在用户提交之前保存用户的输入(如果您愿意,可以像控制台Scanner对象)。我的主类有一个从用户那里获取输入的方法。对于Scanner对象,这很容易做到:scannerObject.nextLine()。有了这个JTextField,我决定使用键绑定来确定何时按下 Enter 键以"提交"JTextField的内容。我设置了键绑定没有问题,但是我不知道如何让主程序等到按下Enter键来查找文本。如果我使用循环,程序会卡住并且无法注册按键。

这是一个尝试从JTextField获取输入的方法:

public static String getStrInput() {
// Request input
display.print(">> ");
needInput = true;
nextInput = "";
// Wait until a string is input from the text field
while (nextInput.isEmpty());    // Wait
needInput = false;
return nextInput;
}

下面是在我的键绑定类中按 Enter 键时的事件处理程序:

private class SubmitAction extends AbstractAction implements ActionListener {
/**
* Makes Java happy.
*/
private static final long serialVersionUID = 1L;
/* -- Constructor -- */
public SubmitAction() {
}
/* -- Method -- */
@Override
public void actionPerformed(ActionEvent e) {
if (Game.needInput())
Game.submitTextField();
}
}

注意:submitTextField()方法所做的只是调用textField.getText()方法并将nextInput字段(请参阅我的第一个方法)设置为返回的字符串。

应该发生的情况是应该注册输入请求(这是needInput = true行),然后 Key Binding 类应在按下 Enter 键时提交文本字段(因为Game.needInput()条件现在返回 true)。但是,在我的getStrInput()方法中,程序卡在while (nextInput.isEmpty());循环中。我认为这会发生,但我不知道如何让主程序等到键绑定的事件处理程序让文本字段提交其内容。

如果这完全没有意义,或者我需要透露更多代码,我会很乐意详细说明。我花了一整天的时间研究这个小问题,只是为了找到挫折感。

有了这个 JTextField,我决定使用键绑定来确定何时按下 Enter 键,以便"提交"JTextField 的内容。

实际上,您应该只是将ActionListener添加到文本字段中。操作侦听器将在按下 Enter 键时被调用。

如果要提示并等待输入文本,则应使用JOptionPane.

最新更新