I have a GUI that has one output text box and one input text box. I would like, if reasonably attainable, to only use the one input box for all user inputs. I have a situation where I ask the user a question, they input their answer, and then inside the method, I'd like to ask a sub-question using that same input text box. However, in the method I created to handle this interaction, so far I am unable to change the text box or press any keys. How should I fix my code?
EDIT: Taking into account comments stating I should not use Thread.sleep(), I attempted to use a Timer instead. However, now instead of waiting, the method immediately fails and returns "N". Forgive me for being relatively new to GUIs and Swing Timers. What do I need to do to have the program wait while still allowing me to type and press enter?
public static String pauseUntilKey(JTextField tf)
{
pause = true;
tf.removeKeyListener(tf.getKeyListeners()[0]);
KeyAdapter pauseForInput = new KeyAdapter() { //Get rid of the old keyAdapter and put in the new one just for this function
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER) //When the enter key is pressed, this should trigger
{
pause = false; //Set local variable pause to be false to let us know we need to stop the while loop
answer = tf.getText();
tf.setText("");
}
}
};
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(pause == false)
timer.stop();
}
});
timer.start();
KeyAdapter enterMain = new KeyAdapter() { //Put the old key adapter back in
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER)
{
roster = textInput(tf.getText(), roster, names, true, tf); //Analyze the line using textInput function, update the roster with any changes
tf.setText("");
}
}
};
tf.addKeyListener(enterMain);
if(pause == false)
return answer; //If we left the while loop the way I wanted, then return whatever the user wrote before pressing enter.
return "N"; //Otherwise, just return N for No.
}