简体   繁体   English

Java Textfield getText()不等待用户输入

[英]Java Textfield getText() does not wait for user input

I have a String called temp that is set to "void" to begin with. 我有一个名为temp的字符串,它首先被设置为“ void”。 I want the while statement to wait for the user to enter some characters in the text box before re evaluating the while loop? 我希望while语句在重新评估while循环之前等待用户在文本框中输入一些字符吗? Currently, it prints "Enter Data" then just continues to set the value of temp to null. 当前,它打印“输入数据”,然后继续将temp的值设置为null。 How would I go about trying to do this? 我将如何去做呢?

String temp = "VOID";

while(UserScreen.textField.getText().equals("") && temp == "")
{
    UserScreen.messageAppend("Enter data");
    temp = UserScreen.textField.getText();
    UserScreen.messageAppend(temp);    
}

The getText() method of textfield your using isnt a blocking method, and will thus be executed as soon as it is called. 您使用的textfield的getText()方法不是阻塞方法,因此将在调用后立即执行。 Your best bet would most likely be to attach a listener to the textfield, for example: 最好的选择是将侦听器附加到文本字段,例如:

textField.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
      temp = UserScreen.textField.getText();
      UserScreen.messageAppend(temp);    
  }
});

The listener gets called when you press enter. 当您按Enter键时,将调用该侦听器。 If you need to listen for every single change in the textfield then use a documentListener instead: 如果您需要侦听文本字段中的每个更改,请改用documentListener:

textField.getDocument().addDocumentListener(new DocumentListener() { ... });

With JTextField you can use an KeyListener for receiving keyboard events (keystrokes). 使用JTextField ,可以使用KeyListener接收键盘事件(击键)。 Something like this: 像这样:

KeyListener keyListener = new KeyListener() {
  public void keyPressed(KeyEvent keyEvent) {
    // here you validation
  }
}
nameTextField.addKeyListener(keyListener);

Also the Temp is VOID therefore should be temp.equals("VOID") 另外Temp是VOID,因此应为temp.equals("VOID")

while(UserScreen.textField.getText().equals("") && temp.equals("VOID"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM