首页 > 解决方案 > Java Swing - 如何暂停方法并等待按键?

问题描述

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

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

标签: javaswinguser-interface

解决方案


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

此外,如果您还没有这样做,您需要使用SwingWorker将调用的实例pauseUntilKey,否则您将锁定整个 swing 子系统,因为它是单线程的。


推荐阅读