Java Swing-如何暂停方法并等待按键?

时间:2019-11-06 16:51:50

标签: java swing user-interface

我有一个GUI,其中有一个输出文本框和一个输入文本框。我希望,如果可以合理实现的话,只将一个输入框用于所有用户输入。我遇到的情况是,我问用户一个问题,他们输入答案,然后在方法内部,我想使用相同的输入文本框提出一个子问题。但是,在我创建的用于处理这种交互的方法中,到目前为止,我无法更改文本框或按任何键。我应该如何修正我的代码?

编辑:考虑到说明我不应该使用Thread.sleep()的注释,我尝试使用Timer。但是,现在该方法不再等待,而是立即失败并返回“ N”。原谅我在GUI和Swing计时器方面还比较陌生。我需要做什么才能让程序等待,同时仍然允许我键入并按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.
}

1 个答案:

答案 0 :(得分:0)

需要将变量pause声明为volatile,否则,事件调度程序线程(将调用keyPressed方法)中所做的更改将永远不会通知工作线程。

此外,如果尚未这样做,则需要使用将调用SwingWorker的{​​{1}}实例,否则将锁定整个swing子系统,因为它是单线程的。